Path Struct Parameters in Axum
Learn how to extract multiple path parameters into a custom struct using Axum's Path extractor with serde deserialization, including field renaming and typed conversions.
When a route contains several path parameters, writing a handler that takes many separate Path<T> arguments becomes messy. Axum lets you group those parameters into a single struct. The handler receives one Path<YourStruct> argument, and Axum fills the struct fields automatically from the URL path. A single segment uses Path<T> with one type, and several segments can go into a tuple, but a struct is the most organized approach when the parameters have names worth keeping.
Why Use a Struct for Path Parameters
A tuple like Path<(u32, String)> works when you have two or three parameters, but it does not tell you what each value means. You must remember that the first element is the user ID and the second is the post slug. A struct gives every field a name, so the handler code reads clearly. It also lets you use serde attributes to rename fields, apply defaults, and validate data in one place.
The core idea: Axum treats the route's path parameters as a set of key-value pairs. If the route is /users/{user_id}/posts/{post_slug}, the keys are user_id and post_slug. Axum passes those pairs to serde's deserializer, which tries to build your struct from them. This is the same mechanism used for query strings, but here the source is the URL path segments.
A Basic One-Parameter Struct
Start with a simple case: one path parameter extracted into a struct that has a single field. The field name must exactly match the route parameter name inside the curly braces.
use axum::{
extract::Path,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UserId {
user_id: u32,
}
async fn get_user(Path(user_id): Path<UserId>) -> String {
format!("Looking for user with ID {}", user_id.user_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}", get(get_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The struct UserId has one field named user_id, which matches the route parameter {user_id}. The handler argument is Path(user_id): Path<UserId>. Inside the handler, you access the field through the struct instance: user_id.user_id. This looks a little redundant for one parameter, but it becomes useful when you have several.
When you run this server and visit http://127.0.0.1:3000/users/42, you will see Looking for user with ID 42. Axum extracted the string "42" from the path, deserialized it into a u32, and put it inside the struct.
Multiple Parameters in One Struct
The real benefit appears with two or more parameters. Define a struct with one field per path segment. The field names must exactly match the parameter names in the route.
use axum::{
extract::Path,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct PostPath {
user_id: u32,
post_slug: String,
}
async fn get_post(Path(path): Path<PostPath>) -> String {
format!(
"Fetching post '{}' for user {}",
path.post_slug, path.user_id
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}/posts/{post_slug}", get(get_post));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The route has two path parameters: {user_id} and {post_slug}. The struct PostPath has fields user_id (a u32) and post_slug (a String). Axum gathers both values, then deserializes the whole set into the struct. The handler receives one Path<PostPath> and can refer to path.user_id and path.post_slug directly.
Visit http://127.0.0.1:3000/users/7/posts/axum-basics and you will see Fetching post 'axum-basics' for user 7.
Struct Extraction Works:
If you see that output, your struct deserialization is set up correctly. The field names matched, the types converted, and Axum filled the struct without any manual parsing.
Renaming Fields with #[serde(rename)]
Sometimes the route parameter name is not a good Rust field name. For example, a route might use {user-id} (hyphen) but Rust field names cannot contain hyphens. Or you may want a field named id in your struct while the route says {user_id}. Serde's rename attribute solves this.
use axum::{
extract::Path,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct PostPath {
#[serde(rename = "user_id")]
id: u32,
#[serde(rename = "post_slug")]
slug: String,
}
async fn get_post(Path(path): Path<PostPath>) -> String {
format!("Fetching post '{}' for user {}", path.slug, path.id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}/posts/{post_slug}", get(get_post));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Here the struct fields are id and slug. The rename attribute tells serde to look for path parameters named user_id and post_slug. The handler still works exactly the same, but the code now uses shorter, more idiomatic field names.
Using Different Data Types
Fields do not have to be strings. Any type that implements serde::Deserialize can be used, as long as the string from the path can be converted. For integers, u32, i64, and usize work out of the box. For a custom type, you need to implement Deserialize yourself; one common way is to write a deserialize_with function, or a try_from function, that calls the type's FromStr implementation and turns the result into a value.
In the examples above, user_id is a u32. If the path contains something that is not a valid number, Axum will fail the extraction and return an error response to the client.
use axum::{
extract::Path,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct DatePath {
year: u16,
month: u8,
day: u8,
}
async fn show_date(Path(date): Path<DatePath>) -> String {
format!("Date: {}-{:02}-{:02}", date.year, date.month, date.day)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/calendar/{year}/{month}/{day}", get(show_date));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
A request to http://127.0.0.1:3000/calendar/2025/12/25 returns Date: 2025-12-25. If you visit /calendar/abc/12/25, Axum cannot parse "abc" into a u16 and will return a 400 Bad Request response.
What Happens When Extraction Fails
Axum's Path extractor uses serde to deserialize the path parameters. If the deserialization fails - because a parameter is missing, a type conversion fails, or a renamed field is not found - the extractor returns an error. That error becomes a response with status 400 Bad Request (or 500 in some edge cases, but normally 400). Your handler will not run. This is consistent behavior across all extractors that use serde.
For example, if your route is /users/{user_id} and your struct expects a field named user_id but the route parameter is {id}, the extraction will fail because the key user_id is not present. Axum will respond with 400 Bad Request. This is why the names must match or you must use rename.
When to Prefer a Struct Over a Tuple
Tuple extraction, Path<(u32, String)>, puts the values in order without names. So when should you choose one over the other?
- Use a tuple when you have only two or three parameters, the order is obvious, and you want the shortest possible handler signature. The downside is that field access is positional (
params.0,params.1), which can be unclear. - Use a struct when there are three or more parameters, when the meaning of each parameter matters, or when you want to rename fields, apply defaults, or reuse the same struct in multiple handlers. Structs make the code self-documenting.
There is no rule that says one is always better. The choice is about readability and maintainability: tuples are shorter, structs are self-documenting.
Optional Path Parameters Are Not Supported
Unlike query parameters, path parameters in a route must always be present for the route to match. You cannot define a route segment that is sometimes absent: if the route is /users/{user_id}/posts/{post_slug}, a request to /users/7/posts will not match the route at all, so no extraction happens.
That does not mean every field in your struct must be a required value. An Option<T> field whose parameter is absent from the route simply deserializes to None: a struct with id: u32 and extra: Option<String> used with the route /users/{id} returns 200 for a request to /users/42, with extra set to None. Serde fills in None for a missing Option field automatically, with no attribute needed. The Option field is only useful when the same struct is shared between path and query extraction, or when the field may be present on some routes and absent on others; it cannot make a path segment itself optional.
If you need optional data, put it in the query string or define multiple routes with different path structures.
Common Mistakes and Misunderstandings
Field Name Mismatch:
The most common mistake is a field name that does not match the route parameter name exactly, including capitalization. Rust field names are case-sensitive, and serde matching is case-sensitive as well. {user_id} and {userId} are different keys. Use rename to fix mismatches.
Missing Deserialize Derive:
If you forget #[derive(Deserialize)] on your struct, the code will not compile when you try to use it with Path<T>. Axum requires T: DeserializeOwned for Path<T>. The compiler error will mention that the trait bound is not satisfied. Always add the derive and ensure serde is a dependency with the derive feature enabled.
Struct Can Have Extra Fields Only with Defaults:
If you define a struct with a field that is not present among the path parameters, serde will fail unless that field has a default: an Option<T> field defaults to None automatically, and any other field needs #[serde(default)] on the field or on the struct. However, adding defaults for missing path parameters is almost never useful because the route itself requires the parameter to exist. Use this only if you have a struct shared between path and query extraction where some fields are optional.
Example: A Complete Server Using Struct Path Parameters
Here is a small but complete application that manages a blog. It has two routes, each using a struct to extract path parameters. This example includes the Cargo.toml dependencies and the full main.rs.
First, create a new project:
cargo new blog_api
cd blog_api
cargo add axum tokio --features tokio/full
cargo add serde --features derive
Now replace src/main.rs with:
use axum::{
extract::Path,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UserPostParams {
user_id: u32,
post_slug: String,
}
#[derive(Deserialize)]
struct UserCommentParams {
#[serde(rename = "user_id")]
author_id: u32,
post_slug: String,
comment_id: u64,
}
async fn get_post(Path(params): Path<UserPostParams>) -> String {
format!(
"Post '{}' by user {}",
params.post_slug, params.user_id
)
}
async fn get_comment(Path(params): Path<UserCommentParams>) -> String {
format!(
"Comment {} on post '{}' by author {}",
params.comment_id, params.post_slug, params.author_id
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}/posts/{post_slug}", get(get_post))
.route(
"/users/{user_id}/posts/{post_slug}/comments/{comment_id}",
get(get_comment),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The first route uses a struct with fields matching the route names. The second route uses rename to change user_id to author_id inside the handler, while still expecting {user_id} in the URL. The comment_id is a u64, showing that different integer types can be used.
Run the server with cargo run, then test with curl:
curl http://127.0.0.1:3000/users/10/posts/axum-tips
# Output: Post 'axum-tips' by user 10
curl http://127.0.0.1:3000/users/10/posts/axum-tips/comments/5
# Output: Comment 5 on post 'axum-tips' by author 10
How Axum Builds the Struct
Under the hood, the Path<T> extractor collects the path parameters from the matched route into an internal map of strings. For /users/{user_id}/posts/{post_slug}, that map contains two entries: "user_id" => "10" and "post_slug" => "axum-tips". Then Axum passes this map to serde's deserializer for T. Serde sees a map of strings and uses the field names (or their rename values) to pick out the values and convert them. This is why the field names are so important - they are the keys in that map.
A tuple struct also works: Path<Params> where struct Params(u32, String) is deserialized positionally, exactly like a tuple. What does not work is a struct whose field names do not match any route parameter and have no default: serde then fails with a missing-field error.
Summary
Path struct parameters give you a clean, named way to receive multiple URL segments in one handler argument. They rely on serde deserialization, so you get type conversion and validation for free. Remember to match field names to route parameter names or use rename, derive Deserialize, and remember that an Option<T> field deserializes to None when its parameter is absent from the route, even though it cannot make a route segment itself optional. With this technique, your handler signatures become self-documenting and your code stays maintainable as the number of path parameters grows.