Answer#
Each route call binds a path to a method router. Chain methods on one path (get(list).post(create)), and axum answers 405 Method Not Allowed for other methods on that path and 404 Not Found for unknown paths.
use axum::{body::{to_bytes, Body}, extract::Path, http::Request, routing::get, Router};
use tower::ServiceExt;
async fn list() -> &'static str { "all users" }
async fn create() -> &'static str { "created" }
async fn show(Path(id): Path<u32>) -> String { format!("user {id}") }
async fn repo(Path((org, name)): Path<(String, String)>) -> String { format!("{org}/{name}") }
async fn rest(Path(p): Path<String>) -> String { format!("rest = {p}") }
fn app() -> Router {
let users = Router::new()
.route("/", get(list).post(create))
.route("/{id}", get(show));
Router::new()
.nest("/users", users)
.route("/repos/{org}/{name}", get(repo))
.route("/files/{*path}", get(rest))
}
#[tokio::main]
async fn main() {
let app = app();
for (method, uri) in [
("GET", "/users"), ("POST", "/users"), ("GET", "/users/7"), ("GET", "/users/abc"),
("DELETE", "/users/7"), ("GET", "/repos/rust-lang/rust"), ("GET", "/files/a/b/c.txt"), ("GET", "/nope"),
] {
let req = Request::builder().method(method).uri(uri).body(Body::empty()).unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let status = res.status().as_u16();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{method} {uri} -> {status} {}", String::from_utf8_lossy(&body));
}
}Output:
GET /users -> 200 all users
POST /users -> 200 created
GET /users/7 -> 200 user 7
GET /users/abc -> 400 Invalid URL: Cannot parse `abc` to a `u32`
DELETE /users/7 -> 405
GET /repos/rust-lang/rust -> 200 rust-lang/rust
GET /files/a/b/c.txt -> 200 rest = a/b/c.txt
GET /nope -> 404 How to read it:
{id}captures one path segment.Path<u32>converts it, and a segment that does not parse (abc) gives400with a message that names the problem.Path<(String, String)>takes several parameters in the order they appear in the path.{*path}captures the rest of the path, including slashes.nest("/users", router)puts a whole router under a prefix, so the inner routes are written without it.
Common mistakes#
- Writing
:id(the syntax of older axum versions). See the thread on the "Path segments must not start with:" panic. - Forgetting that a path with the wrong method is not a 404: the output above shows
DELETE /users/7answering 405, which means the path exists.
Related questions#
How do I read the route's parameters and the query string together?#
Use both extractors as separate arguments: Path(id): Path<u32> and Query(q): Query<Params>.
Can I name the parameters in a struct instead of a tuple?#
Yes. Path<MyParams> works with a struct that derives Deserialize and has a field for each {name}.
Sources#
- axum,
Router: https://docs.rs/axum/0.8.9/axum/struct.Router.html (read 2026-12-05) - axum,
Path: https://docs.rs/axum/0.8.9/axum/extract/struct.Path.html (read 2026-12-05)