Path single parameter
How to extract one dynamic path segment as a String in Axum handlers, with practical examples and common mistakes.
When a URL contains a changing value inside the path - like /users/42 or /products/rust-book - you need a way to grab that value inside your handler. Axum gives you the Path extractor for exactly this job. This page focuses on the simplest case: extracting a single path parameter as a String. You will learn how to define the route, write the handler, use the extracted value, and avoid the mistakes that beginners hit most often.
A Minimal Example with One Path Parameter
Start with a brand new Axum project (the environment setup is assumed to be complete). Create a main.rs file with the following code:
use axum::{
extract::Path,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(show_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();
}
async fn show_user(Path(id): Path<String>) -> String {
format!("You asked for user with id: {}", id)
}
The route definition uses {id} to tell Axum that this part of the path is dynamic. The braces mark a placeholder that matches any single segment; they are not part of the actual URL. The handler function receives a Path<String> extractor, and Axum fills the inner String with whatever appeared in that segment. Run the server and open http://127.0.0.1:3000/users/42 in a browser. You will see the text You asked for user with id: 42. If you visit /users/alice, the same handler runs and prints You asked for user with id: alice.
This works because Path<T> is an extractor that implements FromRequestParts. When Axum calls your handler, it looks at the parts of the request (which include the parsed path segments), finds the segment that corresponds to {id}, and tries to deserialize it into the type you asked for. For String, deserialization succeeds for every valid UTF-8 segment.
Understanding How the Route Matches
Axum uses a router that compares the incoming request path against the patterns you defined. The pattern /users/{id} matches exactly two segments: the first must be the literal word users, and the second can be anything. That second segment is captured and stored for extraction.
If you visit /users, Axum does not match this route because there is no second segment. If you visit /users/42/extra, it also does not match because there are three segments. The match is exact in terms of the number of segments. The dynamic part {id} matches one complete segment. A segment is defined by the slash (/) boundaries. So {id} will never contain a slash.
// This route matches /users/anything but not /users or /users/a/b
.route("/users/{id}", get(show_user))
This is important to remember because beginners often think {id} can match a whole sub‑path. It cannot. If you need to capture multiple segments or a wildcard, that requires a different feature not covered on this page.
Segments arrive percent-decoded:
Axum percent-decodes a captured segment before handing it to your handler, so a request to /users/hello%20world gives your handler the string hello world, with a real space. You never have to decode %20 or %2F yourself.
Using the Parameter in Different Response Types
The previous example returned a plain String. In real applications you often want to return JSON or some other type. The extraction logic stays the same; only the handler's return type and the construction of the response change.
Here is a handler that returns a JSON response containing the extracted id. It uses the serde_json crate, so add serde_json = "1" to the [dependencies] section of your Cargo.toml first:
use axum::{
extract::Path,
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
};
use serde_json::json;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(show_user_json));
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();
}
async fn show_user_json(Path(id): Path<String>) -> impl IntoResponse {
let body = json!({
"user_id": id,
"message": "User details would go here"
});
(StatusCode::OK, Json(body))
}
The function now returns impl IntoResponse because it produces a tuple (StatusCode, Json). Both StatusCode and Json implement IntoResponse, so the tuple can be converted into a response. The extraction of id is identical to before. When you visit http://127.0.0.1:3000/users/7, the browser shows raw JSON: {"user_id":"7","message":"User details would go here"}. Notice that the id remains a string, even though 7 looks like a number. That is because we used Path<String>. If you need a numeric id, you can change the type, but then you must handle the case where the segment is not a valid number: a typed parameter rejects the request before your handler runs.
Multiple Routes, Same Parameter Name
You can have several routes that each use {id}. Axum treats each route separately, and the parameter name {id} is local to that route. You do not need to use different names in different routes, although you can if it makes your code clearer.
use axum::{
extract::Path,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(get_user))
.route("/posts/{id}", get(get_post))
.route("/products/{id}", get(get_product));
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();
}
async fn get_user(Path(id): Path<String>) -> String {
format!("User id: {}", id)
}
async fn get_post(Path(id): Path<String>) -> String {
format!("Post id: {}", id)
}
async fn get_product(Path(id): Path<String>) -> String {
format!("Product id: {}", id)
}
Each handler receives its own Path<String>. When a request comes in, Axum first matches the route (e.g., /posts/abc), then extracts the dynamic segment and passes it to the handler. The parameter name {id} does not have to match the variable name in the handler. In the handler you can name the inner variable whatever you like - it is only the position of the segment in the path that matters. For example, the following handler is perfectly valid:
async fn get_user(Path(user_identifier): Path<String>) -> String {
format!("User id: {}", user_identifier)
}
The route still uses {id}, but the extracted value is stored in user_identifier. The Path extractor matches by position, not by name.
What Happens When the Path Does Not Match
If a request comes in with a path that does not match any route, Axum returns a 404 Not Found response automatically. This happens before your handler is ever called. For the route /users/{id}, requests like /users or /users/ (depending on trailing slash behavior) will result in a 404. The exact behavior with trailing slashes can vary between Axum versions; by default, Axum does not treat /users and /users/ as the same. You can configure this if needed, but it is outside the scope of this page.
Missing segment is not a handler error:
If the URL does not include the required dynamic segment, your handler will not run. You cannot detect a missing parameter inside the handler because the router rejects the request before extraction. Do not try to write code that checks for a missing id inside a handler for a route like /users/{id} - that situation can never reach the handler.
This is different from optional parameters: a route with {id} always requires exactly one segment there, and there is no way to make that segment optional in the route itself. If the segment is absent, the router answers 404 and your handler never runs.
Extracting a Numeric Parameter (Brief Preview)
Although this page concentrates on String, it is natural to ask about numbers. Axum's Path extractor works with any type that implements serde::Deserialize. That includes u32, i64, and other primitive numeric types. For example:
use axum::{
extract::Path,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(get_user_id));
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();
}
async fn get_user_id(Path(id): Path<u32>) -> String {
format!("User id as number: {}", id)
}
When you visit /users/42, the handler runs and prints User id as number: 42. The string "42" from the path is deserialized into a u32. However, if you visit /users/hello, the handler is not called. Axum tries to deserialize the segment into u32, fails, and returns a 400 Bad Request rejection with a plain-text body describing the failure. Be aware that using a typed parameter changes the failure mode from "always succeeds" to "may reject the request before your handler runs."
Typed parameters can reject the request:
When you use Path<u32> or any other non-String type, a malformed segment will cause Axum to return a plain text 400 Bad Request before your handler executes. This happens regardless of what your handler returns, because the rejection short-circuits before the handler is called. You must not assume that every request reaches your handler when using typed parameters.
For most simple routes where you just need to identify a resource and then look it up in a database, using String is safer because you can handle invalid values yourself (e.g., by parsing inside the handler). That is why this page's primary example uses String.
Multiple Ways to Extract a Single Parameter
So far we have used Path(id): Path<String> directly as a function argument. There is another pattern where you destructure the Path after receiving it:
async fn handler(path: Path<String>) -> String {
let id = path.0; // Access the inner String
format!("The id is {}", id)
}
Path is a tuple struct with one public field 0. You can access it as path.0 and then use the value. This style is useful if you want to give the extractor a variable name that is different from the inner value, or if you need to pass the whole Path to a helper function.
use axum::{
extract::Path,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/items/{id}", get(item_handler));
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();
}
async fn item_handler(path: Path<String>) -> String {
let id = path.0;
format!("Item id: {}", id)
}
Both forms are equivalent. The destructuring form Path(id): Path<String> is more common because it saves a line and makes the intent clear. Choose whichever reads better in your code.
Using the Parameter Inside a More Complex Handler
A real handler often does more than just echo the id. It might query a database, call another service, or build a response based on the id. The extraction stays the same, but you can see how the id flows through the function:
use axum::{
extract::Path,
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
};
use serde_json::json;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/books/{isbn}", get(book_details));
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();
}
async fn book_details(Path(isbn): Path<String>) -> impl IntoResponse {
// Simulate looking up a book by ISBN
let title = match isbn.as_str() {
"978-3-16-148410-0" => "The Rust Programming Language",
"978-0-13-235088-4" => "Clean Code",
_ => "Unknown book",
};
let payload = json!({
"isbn": isbn,
"title": title,
"available": true
});
(StatusCode::OK, Json(payload))
}
When you visit http://127.0.0.1:3000/books/978-3-16-148410-0, the handler receives the ISBN as a string, uses it to look up a title, and returns a JSON object. The pattern matching inside the handler is a simple example; in a real application you would query a database. The important point is that the path parameter arrives as a regular Rust String and you can use it like any other string.
Common Mistakes and Misconceptions
Several problems trip up beginners when they start using path parameters.
Mistake 1: Forgetting the braces in the route.
If you write .route("/users/id", get(handler)), Axum treats id as a literal word. The URL /users/id will match, but /users/42 will not. The curly braces are essential to mark a segment as dynamic. Axum 0.7 and later use {id}; the older :id syntax from Axum 0.6 is no longer accepted and panics at route registration with the message "Path segments must not start with :. For capture groups, use {capture}."
// Wrong: matches only /users/id
.route("/users/id", get(handler))
// Wrong: panics when the router is built (Axum 0.7 and later)
.route("/users/:id", get(handler))
// Correct: matches /users/anything
.route("/users/{id}", get(handler))
Mistake 2: Using the wrong extractor type.
Path<String> expects a single string segment. If you accidentally use Path<(String, String)> for a route with only one dynamic segment, the extraction will fail and the request will be rejected with a 500 Internal Server Error, because a wrong number of parameters is treated as a mistake in the handler signature rather than a client error. Always make the number of inner types match the number of dynamic segments in the route. This page covers only one segment, so use exactly one inner type.
Mistake 3: Trying to access path parameters from a different extractor.
Path parameters are only available through Path. You cannot get them from Query or HeaderMap. The Path extractor is the sole mechanism for reading segments matched by {name} in the route.
Mistake 4: Assuming the parameter is automatically converted to a number.
As shown earlier, Path<String> always gives you a string. If you need a number, you must either use Path<u32> and handle rejections, or parse the string inside your handler with id.parse::<u32>(). The latter gives you more control because you can return a custom error message.
You are on the right track when...:
If you define a route with a single dynamic segment, use Path<String> in the handler, and the handler runs with the segment value you expect from the URL, everything is working correctly. Test by visiting different URLs with different segment values and confirming the output changes accordingly.
Summary
Extracting a single path parameter in Axum boils down to three steps: mark the dynamic segment in the route with curly braces, add Path<Type> to your handler's argument list, and use the extracted value inside the function. The simplest and most forgiving type is String, which succeeds for every valid UTF-8 segment. For numeric or other typed parameters, the extraction can fail, and Axum will return an error before your handler runs.
The key insight is that path parameters are positional: the order of the segments in the route determines which value lands in which extractor position. You can name the handler variable anything you want, but the type must match what you expect from that segment. Once you have this single‑parameter pattern down, you can move on to extracting multiple parameters using tuples or structs, which build on exactly the same mechanics.