Multiple path parameters in Axum
Learn how to define routes with two or more path parameters in Axum, extract them into handlers, and avoid common ordering and type mistakes.
When a URL contains more than one variable segment, you need multiple path parameters. A route like /users/42/posts/17 has two dynamic pieces: the user ID and the post ID. Axum lets you capture both and pass them to a handler as separate values or as a structured object. This page shows how to handle several at once.
A first route with two parameters
Start with the simplest possible case: a route that expects exactly two path parameters. Suppose you have an endpoint for a specific comment on a specific post. The URL pattern is /posts/{post_id}/comments/{comment_id} - written with curly braces around each parameter name. (The old colon form, /posts/:post_id/..., panics at registration in Axum 0.8.)
use axum::{routing::get, Router, extract::Path};
async fn show_comment(Path((post_id, comment_id)): Path<(u32, u32)>) -> String {
format!("Post {} comment {}", post_id, comment_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/posts/{post_id}/comments/{comment_id}", get(show_comment));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here Path<(u32, u32)> is an extractor that takes the two path parameters and turns them into a tuple (post_id, comment_id). The order of the tuple fields must match the order the parameters appear in the URL pattern. If you run this server and visit http://127.0.0.1:3000/posts/7/comments/12, the handler returns Post 7 comment 12. A missing segment gives a 404, as in /posts/7/comments, while a segment that cannot parse as a number gives a 400, as in /posts/abc/comments/12.
Route works:
If you see Post 7 comment 12 in your browser, the route and extractor are set up correctly. The tuple extraction is the quickest way to get multiple parameters when you have only a few.
How Axum turns URL segments into values
Behind the scenes, Axum's Path extractor works like a specialized deserializer. For each named parameter in the route (the parts inside {}), Axum captures the raw string segment from the URL. Then it tries to convert those strings into the types you asked for. When you write Path<(u32, String)>, Axum knows to expect two values, and it tries to parse the first as a u32 and the second as a String. The conversion is done entirely with serde::Deserialize - every type you extract, from u32 to a custom struct, must implement Deserialize. It is not FromStr-based.
A beginner can think of Path<(T1, T2)> as a small machine: you give it the route pattern and the URL, and it splits the dynamic parts, converts each part to the type you specified, and hands you a tuple. If any conversion fails (e.g., you wrote abc but expected u32), the extractor rejects the request, and Axum returns a 400 Bad Request by default. That is different from a route mismatch, which gives 404.
The parameter names inside the braces don't have to match the tuple variable names. In the example above, the route says {post_id} and {comment_id}, but the tuple is (post_id, comment_id). The names in the path are just for readability; Axum uses their position, not their names. So you could name them {a} and {b} and still extract them in the same order.
Using a custom struct for clarity
When you have more than two or three parameters, a tuple becomes hard to read because you have to remember which position means what. Instead, you can define a struct that implements Deserialize from serde and use Path<YourStruct>. Axum will match the URL parameter names to the struct fields and build the struct for you.
First, add serde to your Cargo.toml if you haven't already:
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
Now define a struct for the same two parameters:
use axum::{routing::get, Router, extract::Path};
use serde::Deserialize;
#[derive(Deserialize)]
struct CommentPath {
post_id: u32,
comment_id: u32,
}
async fn show_comment_struct(Path(params): Path<CommentPath>) -> String {
format!("Post {} comment {}", params.post_id, params.comment_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/posts/{post_id}/comments/{comment_id}", get(show_comment_struct));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice that the struct field names post_id and comment_id are exactly the same as the placeholder names in the route path. Axum uses those names to match the URL segments. If you rename a struct field, the parameter must be renamed in the route too. This approach becomes much more maintainable when you have four or five parameters, or when you want to attach validation logic to the struct.
Struct field names matter:
With a custom struct, Axum matches by field name, not by order. That means you can reorder the fields in the struct and the URL pattern can stay the same - as long as the names still match. With a tuple, order is everything.
Mixing different types
Path parameters are not limited to integers. You can capture strings, UUIDs, booleans, or any type that implements serde::Deserialize. A common real-world pattern is a route that takes a username (a String) and a numeric ID:
use axum::{routing::get, Router, extract::Path};
async fn user_file(Path((username, file_id)): Path<(String, u32)>) -> String {
format!("User {} requested file {}", username, file_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{username}/files/{file_id}", get(user_file));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Visiting /users/alice/files/99 returns User alice requested file 99. The first parameter is a String, so any non-empty string works, including digits. The second must be a valid u32, so /users/alice/files/not-a-number will produce a 400 Bad Request because the conversion fails.
If you need a more structured type, you can use Uuid from the uuid crate with the serde feature. But that's beyond the scope of multiple parameters; the point is that each segment is independently converted to the type you requested.
Three parameters and beyond
There is no fixed limit on how many path parameters you can have. A route like /orgs/{org_id}/teams/{team_id}/members/{member_id} takes three parameters. With a tuple, that would be Path<(u32, u32, u32)>, but a struct is far clearer:
use axum::{routing::get, Router, extract::Path};
use serde::Deserialize;
#[derive(Deserialize)]
struct MemberPath {
org_id: u32,
team_id: u32,
member_id: u32,
}
async fn show_member(Path(params): Path<MemberPath>) -> String {
format!(
"Org {} team {} member {}",
params.org_id, params.team_id, params.member_id
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route(
"/orgs/{org_id}/teams/{team_id}/members/{member_id}",
get(show_member),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler receives a fully populated MemberPath. If any of the three segments cannot be converted to the type you asked for, the request fails with a 400 before your handler runs. If a segment is missing entirely, the route does not match at all and the request gets a 404. That is a big benefit: your handler code only runs when all parameters are present and valid.
Common mistakes and how to fix them
Several beginner errors happen repeatedly with multiple path parameters. Recognizing them early will save you a lot of confusion.
Wrong order in a tuple
If you write Path<(u32, u32)> but the route is /posts/{comment_id}/comments/{post_id}, the first tuple element will receive the first URL segment, not the one whose name matches comment_id. This is the most frequent mistake because the names in the route can be misleading. The tuple extractor completely ignores the names and uses position only.
Fix: Always order your tuple fields in exactly the same order as the segments appear in the path. If you want name-based matching, use a struct.
Tuple order is positional:
With Path<(A, B)>, the first type A always corresponds to the first {param} in the path, and B to the second, regardless of what you name the braces. A reader who expects name-based matching will get swapped values and likely a bug that only appears for certain inputs.
Type mismatch
If you ask for u32 but the URL contains -5 or 99999999999999999999 (too large), the conversion fails and Axum returns 400 Bad Request. Beginners sometimes expect Axum to just pass the string through. It doesn't; it tries to parse into the type you declared. If you really need the raw string, use String, but then you must validate it yourself.
Wrong type causes 400:
A request like /posts/abc/comments/12 when you declared u32 will not reach your handler. Axum's extractor rejects it and returns 400 Bad Request automatically. If you're getting 400 errors and you didn't write any validation, check the types in your Path extractor.
Missing serde derive
Using a custom struct without #[derive(Deserialize)] will cause a compile error because Path<YourStruct> cannot know how to fill the struct. The error message often mentions that YourStruct does not implement Deserialize. Add the derive and ensure serde is in your dependencies.
Forgetting to match all parameters
A route pattern must include every parameter you try to extract. If you have Path<(u32, u32)> but the route only has one {id}, the program still compiles - the mismatch fails at runtime, when a request arrives, with a 500 Internal Server Error ("Wrong number of path arguments for Path. Expected 2 but got 1"). Similarly, if your struct has three fields but the route only has two {...} placeholders, extraction fails at runtime with a 400 Bad Request for the missing field. Nothing about placeholder counts is checked at compile time.
Incorrect field names in struct
With a struct, field names must exactly match the placeholder names in the route. {post_id} in the path and post_id in the struct are fine. {postId} and post_id will not match because case matters. This is a common subtle error.
A realistic nested resource example
Many APIs represent relationships between resources with nested paths. For example, a blog system might have /users/{user_id}/posts/{post_id} to fetch a single post written by a specific user. That route uses two parameters: the user ID and the post ID. Let's build a tiny handler that looks up a post from an in-memory map. For demonstration, we'll use a simple HashMap keyed by (u32, u32).
use axum::{routing::get, Router, extract::Path, http::StatusCode, response::IntoResponse};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
posts: Arc<HashMap<(u32, u32), String>>,
}
async fn get_user_post(
Path((user_id, post_id)): Path<(u32, u32)>,
axum::extract::State(state): axum::extract::State<AppState>,
) -> impl IntoResponse {
match state.posts.get(&(user_id, post_id)) {
Some(content) => (StatusCode::OK, content.clone()),
None => (StatusCode::NOT_FOUND, "Post not found".to_string()),
}
}
#[tokio::main]
async fn main() {
let mut posts = HashMap::new();
posts.insert((1, 101), "User 1's first post".to_string());
posts.insert((2, 202), "User 2's second post".to_string());
let state = AppState {
posts: Arc::new(posts),
};
let app = Router::new()
.route("/users/{user_id}/posts/{post_id}", get(get_user_post))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now visiting http://127.0.0.1:3000/users/1/posts/101 returns User 1's first post, and /users/1/posts/999 returns Post not found. Notice the handler takes two extractors: Path and State. Axum can combine multiple extractors as separate function arguments, each with its own job. The Path handles the URL parameters, and State gives access to shared application data. This pattern is very common in real applications.
Choosing between tuple and struct
For two or three parameters, a tuple is quick and readable. For more parameters, or when the same set of parameters is used in several handlers, a struct is better because it gives named fields and can be reused. A struct also lets you add custom validation methods. The choice is about clarity, not capability.
If you have many handlers that share the same path pattern, you can define the struct once and use Path<MyParams> in each handler. That keeps the route definitions consistent and avoids mistakes in tuple ordering.
How beginners should think about multiple path parameters
Imagine the URL as a set of labeled boxes. Each {name} in the route pattern is a box that will hold exactly one segment from the actual URL. Axum's job is to open each box, look at the string inside, and convert it to the type you requested. If you ask for a tuple, Axum hands you the boxes in the order they appear. If you ask for a struct, Axum matches the labels to the field names and then fills them. This mental model makes it clear why order matters for tuples and why names matter for structs.
When you design a route, ask yourself: "What information does this handler need from the URL to do its job?" Then list those pieces in the order they naturally appear in the path, or as a struct with descriptive field names. That will help you avoid mistakes and make the code self-documenting.
Summary
Multiple path parameters are just an extension of single parameters: you declare more than one placeholder in the route pattern and then extract them together. The two main extraction styles are a tuple (positional) and a custom struct (name-based). The choice depends on readability and reuse. The most important thing to remember is that Axum converts each segment to the type you ask for, and any failure results in an error response before your handler runs. Once you can handle two parameters, you can handle any number, and you're ready to build routes that model complex relationships between resources.