FAQ - Help and questions

How do I define routes, path parameters and nested routers in axum?

#axum#routing#web#path-parameterspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Use Router::route with a path and a method router such as get(h).post(h2). Write path parameters as {name} and read them with the Path extractor. Group routes with Router::nest, and use {*rest} to capture the remainder of a path. Unknown paths give 404 and wrong methods give 405.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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:

text
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) gives 400 with 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/7 answering 405, which means the path exists.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet