Path tuple length mismatches
Learn what happens in Axum 0.8 when the number of path parameters in a route does not match the tuple length of a Path extractor, and how the runtime errors differ for tuples, single values, and structs.
When you extract multiple values from a URL path in Axum, you often use a tuple. For example, a route like /users/{user_id}/posts/{post_id} can be handled by a function that takes Path<(u32, u32)>. A common bug is getting the numbers wrong: you think you are extracting three values but your route only has two path parameters, or the other way around. Axum does not check this at compile time. The route string is just a &str passed to .route(), and the compiler sees no connection between it and your handler, so mismatched code compiles fine. The failure shows up at runtime, when a request arrives, and the status code and message depend on what kind of type you extract into.
This page explains what actually happens when the numbers do not match, how the runtime error differs for tuples, single values, and structs, and how to use that knowledge to avoid the bug. We start from the absolute basics of path parameters and tuples, then show many examples of working code and what happens when you get the length wrong.
Understanding path parameters and tuples
Before we talk about the length check, we need to be clear about what a path parameter is and what a tuple is.
A path parameter is a placeholder inside a route path. When you define a route in Axum, you can write something like /users/{id}. The {id} part is a path parameter. When a request comes in for /users/42, Axum captures the value 42 and makes it available to your handler. You extract that value using the Path extractor from axum::extract. For a single parameter, you write Path<u32> and Axum will parse 42 into a u32 and hand it to you.
A tuple is a fixed-size collection of values of possibly different types. In Rust, (u32, String) is a tuple with two elements: a u32 and a String. Tuples are written with parentheses and commas. They are used when you need to group a known number of values together without creating a named structure.
When you have multiple path parameters in a route, you can extract them all at once by using a tuple as the inner type of Path. For example, Path<(u32, String)> will extract two path parameters: the first as u32, the second as String. Axum knows the order because it follows the order of the parameters in the route pattern.
There is no compile-time check
The Path extractor uses Serde to deserialize the captured path parameters into whatever type you specified. If you declared Path<(u32, String)> but your route only had one path parameter, Axum tries to deserialize a sequence of one element into a two-element tuple. That fails at runtime, and Axum returns an internal server error (HTTP 500) to the client, with the body Wrong number of path arguments for \Path`. Expected 2 but got 1`.
This kind of bug is easy to introduce. You might change the route from /users/{id}/posts/{post_id} to /users/{id}/posts but forget to update the handler. Or you might copy-paste a handler from another route and forget to adjust the tuple. The compiler cannot help you, because it does not know how many path parameters the route string contains. The route string is just a &str passed to the .route() method, and the handler is a separate function. The compiler sees no connection between the two.
How the runtime length check works
There is no Capture trait and no ARITY constant anywhere in Axum 0.8: the check happens at runtime, inside the Path extractor, when a request arrives. The extractor counts the captured path parameters and compares that count with how many values the target type expects:
- A single value like
u32expects 1 parameter. A tuple(u32, String)expects 2,(u32, String, i64)expects 3, and so on. - If the counts differ, extraction fails with a
PathRejection::FailedToDeserializePathParamswhose message isWrong number of path arguments for \Path`. Expected but got `. The status code is 500 Internal Server Error. - A struct is different: it is deserialized as a map keyed by parameter name, so a missing field does not trigger the count check. Instead, Serde reports the missing field, and the client gets a 400 Bad Request with a body like
Invalid URL: missing field \post_id``. See the struct section below for the exact behaviour.
A basic working example with one path parameter
Let's start with the simplest possible case: one path parameter extracted as Path<u32>.
use axum::{extract::Path, routing::get, Router};
async fn get_user(Path(user_id): Path<u32>) -> String {
format!("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("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
In this example, the route /users/{user_id} has exactly one path parameter. The handler get_user extracts Path<u32>, which expects exactly one value. When you run the server and visit http://localhost:3000/users/42, Axum captures 42, deserializes it as u32, and the handler returns "User ID: 42".
This is the baseline. When everything matches, there is nothing to notice. The failure only becomes visible when you make a mistake, and then it appears at runtime, not at compile time.
Extracting two path parameters with a tuple
Now let's look at a route with two path parameters extracted as a tuple.
use axum::{extract::Path, routing::get, Router};
async fn get_post(Path((user_id, post_id)): Path<(u32, u32)>) -> String {
format!("User {} requested post {}", user_id, post_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}/posts/{post_id}", get(get_post));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
Here the route has two path parameters: {user_id} and {post_id}. The handler extracts Path<(u32, u32)>, a tuple with two elements, which expects 2 path parameters, and the route provides 2. When you request http://localhost:3000/users/10/posts/25, the handler receives user_id = 10 and post_id = 25.
You can mix types inside the tuple. For example, the first parameter could be a String and the second an i32:
async fn get_product_info(
Path((category, product_id)): Path<(String, i32)>,
) -> String {
format!("Category: {}, Product ID: {}", category, product_id)
}
The route would look like /categories/{category}/products/{product_id}. The order is determined by the position in the tuple and the position in the route.
What happens when the tuple length does not match
Now for the most important part: what happens if you make a mistake and the tuple length does not match the number of path parameters? The code still compiles. There is no compile-time check, so nothing stops you from registering the route. The failure happens at runtime, when a request arrives.
Suppose you have the route /users/{user_id} but you accidentally write a handler that expects two path parameters:
use axum::{extract::Path, routing::get, Router};
async fn get_user_bad(
Path((user_id, something_else)): Path<(u32, String)>,
) -> String {
format!("User ID: {}, Something: {}", user_id, something_else)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{user_id}", get(get_user_bad));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This compiles without any error. But when a client requests /users/42, Axum returns a 500 Internal Server Error with the plain-text body:
Wrong number of path arguments for `Path`. Expected 2 but got 1
The message is clear: the handler expected 2 path arguments but the route only captured 1. The same check applies to any tuple length. If you have three path parameters but extract only two, you get Expected 2 but got 3. If you extract four but the route has only three, you get Expected 4 but got 3. The check is exact, and it always fails at runtime with a 500, never at compile time.
A 500 here means a bug in your code:
If you see this 500 in production, do not try to work around it by adding dummy parameters to the route or removing the tuple. Fix the mismatch: either change the route to include the missing path parameter, or change the handler to extract the correct number of parameters. The 500 is telling you the route and the handler disagree, and only you can reconcile them.
Using a struct instead of a tuple
Sometimes you have more than two or three path parameters, or you want to give them meaningful names. Instead of a tuple, you can define a struct that derives Deserialize and use it as the inner type of Path. For example:
use axum::{extract::Path, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct UserPostParams {
user_id: u32,
post_id: u32,
}
async fn get_user_post(Path(params): Path<UserPostParams>) -> String {
format!("User {} requested post {}", params.user_id, params.post_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}/posts/{post_id}", get(get_user_post));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
This works, and the fields are named user_id and post_id. A struct is deserialized as a map keyed by parameter name, so it behaves differently from a tuple when the counts disagree.
If you change the route to /users/{user_id} but keep the struct with two fields, the code will still compile. When a request comes in, Axum tries to deserialize a map with one path parameter {"user_id": "42"} into UserPostParams. Serde fails because the field post_id is missing, and Axum returns a 400 Bad Request to the client with the body Invalid URL: missing field \post_id``. That is different from the tuple case, which gives a 500: a struct reports the missing field as a deserialization error, not as a wrong-number-of-parameters error. Either way, you only discover the bug at runtime.
No compile-time check for custom structs:
Using Path<MyStruct> is convenient and often more readable than a long tuple, but no length check protects you at compile time, for structs or for tuples. You must manually ensure that the number of fields in your struct matches the number of path parameters in the route. A good practice is to keep the route and the struct definition close together, or to add a comment near the route definition stating the expected struct.
There is no trait you can implement to get a compile-time check for a custom type: no such trait exists in Axum 0.8. The only defence is keeping the route and the handler in sync, and testing the route with a real request.
Why this matters
A tuple length mismatch is a real class of production incident. Consider a web API that has a route /orders/{order_id}/items/{item_id}. A developer refactors the handler to add a third path parameter, maybe a subitem_id, but forgets to update the route. The server compiles fine, deploys, and then every request to that endpoint returns a 500 with Wrong number of path arguments for \Path`. Expected 3 but got 2`. The developer might not notice until users complain. Axum does not stop this at compile time, so the practical defence is to test every route with a real request (even one request per route catches this immediately), and to keep the route and handler next to each other in the code so a change to one prompts a change to the other.
It also encourages better API design. If you know the counts must match exactly at runtime, you are less likely to create routes that are ambiguous or have inconsistent numbers of parameters. You will think carefully about what each segment represents and write handlers that match.
Multiple ways to extract path parameters
You have seen three ways to extract path parameters:
- A single value:
Path<u32> - A tuple of values:
Path<(u32, String)> - A struct that derives
Deserialize:Path<MyStruct>
Each has trade-offs. Use a single value when there is only one path parameter. Use a tuple when there are two or three parameters: a mismatch gives a loud 500 with a clear message naming the expected and actual counts. Use a struct when there are many parameters or you want named fields, but remember that a mismatch there gives a 400 about the missing field instead.
There is a fourth, less common way: you can use a map type like Path<HashMap<String, String>> to get all path parameters as a collection without caring about their order or number. That never fails on length, and you must handle missing or extra parameters yourself. This is useful for dynamic routes with an unknown number of parameters, but it is beyond the scope of this page.
Common mistakes and misconceptions
Here are some common errors people make when working with path tuple length checks in Axum 0.8.
Mistake 1: Thinking there is a compile-time check at all. There is not. No path extractor is checked at compile time: a tuple with the wrong length, a single value on a route with no captures, and a struct with the wrong number of fields all compile fine. The failure always appears at runtime, as a 500 for tuples and single values, or a 400 for structs with a missing field. If you see no compile error when the numbers disagree, that is expected behavior, not a bug in Axum.
Mistake 2: Trying to use Path<(T,)> for a single parameter. In Rust, (T,) is a tuple with one element, and it expects exactly 1 path parameter, same as just T. So Path<(u32,)> behaves like Path<u32>. It will work, but it is unnecessary and confusing. Use Path<u32> instead.
Mistake 3: Forgetting that the order of tuple elements must match the order of path parameters. If your route is /posts/{post_id}/comments/{comment_id} and you write Path((comment_id, post_id)), the compiler will still be happy because the length matches. But the first tuple element always receives the first route segment, so comment_id ends up holding the post ID and post_id ends up holding the comment ID. The types might both be u32, so you will not notice the swap until you use the values and get wrong data. A request to /posts/10/comments/25 with this handler prints comment_id=10 post_id=25, the exact opposite of what the names promise:
// Wrong order: the names do not match the route segments.
async fn get_comment(Path((comment_id, post_id)): Path<(u32, u32)>) -> String {
format!("comment_id={} post_id={}", comment_id, post_id)
}
Always order the tuple elements to match the route pattern left to right.
Mistake 4: Assuming the check catches type mismatches. The length check only cares about the number of elements, not their types. If you write Path<(String, u32)> and both path segments happen to be numeric strings, the extraction will work. String accepts any segment, so it never fails to parse. The danger is with types like u32: if a path segment is not a valid number, extraction fails at runtime with a 400 deserialization error, not with the wrong-number message.
A 500 with the wrong-number message means the counts disagree:
If you intentionally write a route and handler with mismatched tuple lengths just to see what happens, the resulting 500 with Wrong number of path arguments for \Path`. Expected 2 but got 1` is the runtime check doing its job. Fix the counts to match; the message tells you exactly which side is wrong.
Summary
Axum 0.8 does not check at compile time that the number of path parameters in a route pattern matches the number of elements in a Path tuple extractor. There is no Capture trait and no ARITY constant in Axum 0.8. A mismatch compiles fine and fails at runtime: tuples and single values give a 500 with Wrong number of path arguments for \Path`. Expected but got , while a struct with a missing field gives a 400 with Invalid URL: missing field `field``.
The main takeaway: the counts must match exactly, and the only thing that enforces it is a request hitting the route. Use tuples when you want a loud, precise 500 naming the expected and actual counts. Use structs when you need named fields, but add your own discipline to keep them in sync with the route, and test every route with a real request. This page closes the Extractors chapter with a reminder that the compiler cannot see the connection between a route string and its handler, so that connection is yours to maintain.