Typed Path Parameters with u32 in Axum
Learn how to use Path u32 to extract and automatically parse typed path parameters from the URL in Axum handlers, including error handling, common mistakes, and practical examples.
When you build a web API, you often need to accept a number in the URL that identifies a specific resource. For example, a request to /users/42 should let your handler know that the user wants the user with ID 42. Axum's Path extractor can pull that value out of the URL and hand it to you as a typed u32 integer, so you don't have to parse the string yourself. This page teaches you how to use Path<u32> in Axum handlers, what happens behind the scenes, how to handle invalid input, and the common mistakes beginners make.
What a Typed Path Parameter Is
A path parameter is a part of the URL that changes from request to request but follows a fixed pattern. In Axum, you define that pattern when you create a route. For example, the route /users/{user_id} has a parameter named user_id. The {} brackets tell Axum that this part of the path is not a literal string but a placeholder. When a request comes in for /users/42, Axum will capture the segment 42 and make it available to your handler.
The Path extractor is how you ask Axum to give you those captured values. If you write Path<u32> in your handler's arguments, you are asking Axum to take that captured segment, which is originally a string like "42", and convert it into a u32 number for you. u32 is Rust's unsigned 32-bit integer type, which means it can hold whole numbers from 0 up to about 4 billion. That is a natural fit for IDs, counts, and many other numeric identifiers.
About the Path Extractor:
The Path extractor is part of the axum::extract module. You use it by writing Path(some_variable): Path<SomeType> in your handler's parameter list. The angle brackets after Path tell Axum what Rust type you want the path segment to become. For this page, that type is always u32.
Why would you want the value as a u32 instead of just a String? Because a String could contain anything: "42", "hello", "4.2", or even an empty string. By asking for u32, you force Axum to check that the segment really looks like a non-negative whole number, and if it does, you get a real number you can do math with. If it doesn't, Axum will reject the request with an error response before your handler even runs. That automatic validation saves you from writing manual checks and makes your API more predictable.
Your First Path<u32> Handler
Start with the smallest possible example. This handler receives a u32 from the URL and returns a simple text response containing that number. You can paste this into a file like src/main.rs of an Axum project and run it.
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("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Look at the handler signature: async fn get_user(Path(user_id): Path<u32>) -> String. The Path(user_id) part is a pattern match. The Path extractor wraps the actual value, and you destructure it to get the inner u32 bound to user_id. The handler returns a String that includes that number. In main, the route is /users/{user_id}, which tells Axum where the parameter lives.
When you run this and open http://127.0.0.1:3000/users/123 in your browser or with a tool like curl, you should see:
User ID: 123
If you open http://127.0.0.1:3000/users/abc, Axum will not call your handler. Instead, it returns a 400 Bad Request response with an error message in the body. That is Axum protecting your handler from invalid data. You will learn how to control that behavior later.
You Have a Working Typed Path Handler:
If you see User ID: 123 when visiting /users/123, everything is set up correctly. This confirms that Axum captured the path segment and converted it to a u32 exactly as requested.
How Axum Converts the Path Segment to u32
Under the hood, Axum deserializes the path string into the target type with serde. For primitive numbers the deserializer parses the string the same way FromStr does, so u32 needs no conversion code of its own. Note that the requirement is serde::Deserialize, not FromStr: a custom type that only implements FromStr cannot be used in Path<...> until it also has a Deserialize implementation that calls it. The parsing happens before your handler is called, in the extractor layer.
The flow looks like this:
- A request arrives for
/users/42. - Axum matches the route
/users/{user_id}and captures the raw string"42"for the parameter. - The
Path<u32>extractor sees that your handler wants au32. - It calls
"42".parse::<u32>(). - Parsing succeeds, so the extractor yields the number
42. - Your handler runs with
user_id = 42.
If step 4 fails because the string is not a valid u32 (for example, "abc" or "-5" or ""), Axum stops processing and returns a rejection. The rejection is a structured error that eventually becomes a 400 Bad Request response. Your handler never executes, so you don't have to worry about receiving a malformed value.
u32 Does Not Accept Negative Numbers:
Because u32 is unsigned, a path segment like -1 will fail to parse. If you need negative numbers, consider i32 instead. But for this page, we are focusing on u32 for non-negative IDs and counts.
The parsing is strict and follows Rust's FromStr rules for u32: no whitespace and no minus sign, but a leading + and leading zeros are accepted, so "+42" and "0042" both parse to 42. A segment like " 42 " will not parse because FromStr for u32 does not trim whitespace. If you need to accept such variations, you would need to handle it yourself with a custom type, which is beyond the scope of this page.
Handling Invalid Input Inside Your Handler
Sometimes you want to customize the error response when the path segment cannot be parsed as a u32. For example, you might want to return a JSON error with your own structure instead of Axum's default plain text. Axum allows you to receive the Path extractor as a Result<Path<u32>, PathRejection>. This lets you inspect the rejection and decide what to do.
Here is an example that returns a custom error message with a StatusCode::BAD_REQUEST:
use axum::{
extract::{rejection::PathRejection, Path},
http::StatusCode,
routing::get,
Router,
};
async fn get_user_checked(
result: Result<Path<u32>, PathRejection>,
) -> Result<String, (StatusCode, String)> {
match result {
Ok(Path(user_id)) => Ok(format!("User ID: {}", user_id)),
Err(rejection) => {
// Convert the rejection into a user-friendly error
let message = match rejection {
PathRejection::FailedToDeserializePathParams(_) => {
"The user ID must be a positive whole number".to_string()
}
PathRejection::MissingPathParams(_) => {
"The user ID is missing from the URL".to_string()
}
_ => "Invalid user ID".to_string(),
};
Err((StatusCode::BAD_REQUEST, message))
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{user_id}", get(get_user_checked));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler now accepts a Result. On success, it unwraps the Path and returns the same string as before. On failure, it matches against the two most common variants of PathRejection:
FailedToDeserializePathParamsoccurs when the path segment exists but cannot be parsed intou32.MissingPathParamsoccurs when the request carries no path-parameter data at all, which happens whenPathis extracted outside the router, for example in middleware that runs before routing. It is not what you get from a route without a capture (see below).
The catch-all _ handles any future variants. You then return a tuple (StatusCode::BAD_REQUEST, message), which Axum converts into an HTTP response.
Run this and test both /users/123 and /users/abc:
/users/123returns200 OKwith bodyUser ID: 123./users/abcreturns400 Bad Requestwith bodyThe user ID must be a positive whole number.
Unhandled Rejections Become 400 Responses:
If you do not wrap Path<u32> in a Result, Axum will automatically turn a parse failure into a 400 Bad Request with a generic error message. That may be fine for development, but in production you often want a custom message or a different status code. Wrapping in Result gives you that control.
Combining Path<u32> with Other Extractors
A real handler rarely needs only the path parameter. You might also want query parameters, application state, or headers. Axum lets you combine multiple extractors by listing them as separate arguments. The order matters only for the request body extractor, but Path<u32> does not consume the body, so you can place it anywhere among other non-body extractors.
This example adds a query parameter verbose to control the response format:
use axum::{
extract::{Path, Query},
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Params {
verbose: Option<bool>,
}
async fn get_user_details(
Path(user_id): Path<u32>,
Query(params): Query<Params>,
) -> String {
if params.verbose.unwrap_or(false) {
format!("User ID: {} (verbose)", user_id)
} else {
format!("User ID: {}", user_id)
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{user_id}", get(get_user_details));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here we define a Params struct that implements Deserialize (using the serde crate) and accept it as a Query. The handler takes two arguments: Path<u32> and Query<Params>. Axum runs both extractors, and if either fails, the handler is not called. When both succeed, you have access to the typed path value and the parsed query string.
Test with:
http://127.0.0.1:3000/users/42→User ID: 42http://127.0.0.1:3000/users/42?verbose=true→User ID: 42 (verbose)
This demonstrates that Path<u32> works alongside other common extractors without any special configuration.
Route Patterns That Work with Path<u32>
The route pattern must include exactly one capture for each Path extractor in the handler. Axum does not check this at compile time: a handler that expects Path<u32> on a route with no capture compiles without complaint, because the route pattern and the handler signature are not type-checked against each other.
For example, this compiles:
async fn bad_handler(Path(id): Path<u32>) -> String {
format!("{}", id)
}
let app = Router::new().route("/users", get(bad_handler));
The failure appears at runtime instead. A request to /users matches the route, extraction finds zero path parameters where one was expected, and Axum returns a 500 Internal Server Error with body Wrong number of path arguments for `Path`. Expected 1 but got 0. Note that multiple parameters must be extracted with a tuple `Path<(_, _)>` or a struct `Path<YourParams>` . Always check that the route pattern matches the extractor yourself; the compiler will not do it for you.
You can have static prefixes and suffixes around the parameter:
Router::new().route("/api/v1/users/{user_id}/posts", get(get_user_posts));
In that case, the Path<u32> extractor still captures only the {user_id} segment. The other parts are just literal strings in the route.
Common Mistakes to Avoid
Forgetting to Add the Parameter to the Route
As shown above, if you write Path<u32> in your handler but forget to include {...} in the route, the code still compiles, and every request fails at runtime with a 500. Always ensure the route pattern matches the extractor.
Using the Wrong Integer Type
If you use Path<u32> but the path segment contains a number larger than u32::MAX (4,294,967,295), parsing fails. For example, /users/99999999999999999999 will be rejected. If your IDs might be larger, consider u64.
Assuming Whitespace Is Allowed
Path<u32> does not trim spaces. A URL like /users/ 42 will not parse because the path segment is " 42 " (or it may be percent-encoded). Stick to plain numbers without extra characters.
Confusing Path<u32> with a Query Parameter
A path parameter comes from the URL path (/users/42). A query parameter comes after the ? (/users?user_id=42). If you want the latter, use Query instead. Path<u32> only looks at the path part.
Not Handling the Rejection When You Need Custom Logic
If you want to return a specific error status (like 404 Not Found instead of 400) when parsing fails, you must wrap Path<u32> in a Result and handle it. Otherwise Axum always uses 400.
When Path<u32> Is Not Enough
Path<u32> is perfect for a single numeric path parameter. But many routes need multiple parameters, like /users/{user_id}/posts/{post_id}. For that, you would use a tuple or a custom struct that implements Deserialize. This page focuses only on the case where you have one parameter and you want it as a u32.
Similarly, if your path parameter is not a number but a string, you can use Path<String>. Path<u32> is just a convenient, type-safe way to express that the segment must be a non-negative integer.
Summary
You have learned how to extract a typed unsigned 32-bit integer from the URL path using Axum's Path<u32> extractor. The key insight is that by specifying the type, you offload validation and parsing to Axum, which keeps your handler code clean and safe. The extractor works by deserializing the captured string into the target type, and it rejects the request with a 400 if parsing fails, unless you handle the rejection yourself.
When your API relies on numeric IDs, Path<u32> is often the simplest and most robust choice. It pairs well with other extractors like Query and State. Axum does not check route patterns against handler signatures at compile time, so double-check that the route provides every parameter the handler expects. As you move forward, you may want to explore how to handle multiple typed path parameters or how to deserialize a path into a custom struct - those patterns build on the same foundation you have now.