The /users/{id} Route Syntax
Understand how to write a route path that captures a single dynamic segment such as a user ID, using the brace parameter syntax in Axum 0.8.
A dynamic route is one that can match many different URLs instead of just one. For example, instead of writing a separate route for /users/1, /users/2, and /users/3, you write a single route pattern like /users/{id}. The {id} part tells Axum to capture whatever appears in that position of the URL and give it to your handler as a value named id.
Axum has used two different symbols for marking these dynamic segments over its history. The older style used a colon before the parameter name (:id). The newer style, introduced in Axum 0.8, uses curly braces around the parameter name ({id}). In Axum 0.8, only the brace style works: registering a route with :id panics immediately with Path segments must not start with \:`. For capture groups, use ``. The colon form still exists in older tutorials and third-party code written for Axum 0.7, where it was the standard syntax - but on Axum 0.8 it is an error, not a deprecated-but-working alternative. This page explains exactly how the brace syntax works, using /users/` as the reference example.
A Complete Minimal Example
Start with the smallest possible application that defines a route with one dynamic segment. The following code sets up an Axum server that listens on port 3000 and responds to any request where the first path segment is /users and the second segment is any non-empty text.
use axum::{routing::get, Router, extract::Path};
async fn show_user(Path(user_id): Path<String>) -> String {
format!("You asked for user: {}", user_id)
}
#[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();
}
Run the program with cargo run, then open another terminal and test it with a tool like curl:
curl http://127.0.0.1:3000/users/42
The server responds with:
You asked for user: 42
If you request /users/alice instead, the response becomes You asked for user: alice. That single route definition now handles any single word after /users/.
The handler function show_user receives a Path<String> extractor. The route string /users/{id} captures the second segment as a string, and the extractor pulls that captured value into the function. The parameter name in the route (id) does not need to match the variable name inside the handler (user_id), because a single captured value is handed to the handler by position.
How Axum Interprets the Route String
When you call .route("/users/{id}", ...), Axum compiles that string into a path pattern. It splits the string on / characters and looks for segments enclosed in {}. A segment like {id} is treated as a capture that matches exactly one non-empty URL segment. A segment that starts with : is rejected: registering it panics immediately, before the server starts.
The term segment here means a piece of the path between two slashes. In the URL http://example.com/users/42, the path is /users/42, and the segments are users and 42. A dynamic segment matches any text that does not contain a / character. That is why /users/42 matches, but /users/42/profile does not - the pattern has only two segments, and the extra segment after 42 does not fit.
In Axum 0.8 and later, the only syntax is braces. The equivalent of the old 0.7 route /users/:id is:
.route("/users/{id}", get(show_user))
Axum 0.8 does not accept the colon syntax: it panics at registration. If you are migrating old code, replace every :name with {name}. (There is one escape hatch, Router::without_v07_checks(), which disables the check - but then :id is treated as a literal segment that only matches the URL /users/:id, not as a capture. It does not restore the old behavior.) When you read older tutorials or third-party code, you may encounter the colon form; treat it as Axum 0.7 syntax.
use axum::{routing::get, Router, extract::Path};
async fn show_user(Path(user_id): Path<String>) -> String {
format!("User: {}", user_id)
}
let app = Router::new()
.route("/users/{id}", get(show_user));
The two definitions are the same route written in two Axum generations: the brace form is Axum 0.8, the colon form is Axum 0.7. On Axum 0.8 the colon version does not run at all - it panics when the route is registered.
The colon syntax panics on Axum 0.8:
If you are using Axum 0.8 or newer, always use the brace syntax ({id}) for route definitions. The colon syntax (:id) is not deprecated-but-working - registering it panics immediately with Path segments must not start with \:`. There is no deprecation warning and no graceful fallback. Replace every :namewith` when migrating from Axum 0.7.
Extracting the Captured Value in a Handler
The Path extractor is the standard way to receive dynamic path segments. It comes from axum::extract::Path. You can extract the value as a String, or you can ask Axum to convert it to another type such as u64 or i32 for numeric IDs. Axum will attempt to parse the captured segment into the requested type. If the parsing fails, the handler returns a 400 Bad Request response automatically.
Here is an example that expects a numeric user ID:
use axum::{routing::get, Router, extract::Path};
async fn show_user(Path(user_id): Path<u64>) -> String {
format!("User ID is {}", user_id)
}
#[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();
axum::serve(listener, app).await.unwrap();
}
Now request http://127.0.0.1:3000/users/42 and you get User ID is 42. But if you request /users/abc, Axum sends a 400 Bad Request because the string "abc" cannot be turned into a u64.
What happened internally? The route pattern captured the segment "abc" as a String. The Path<u64> extractor then tried to parse that string into a u64. The parse failed, so the extractor rejected the request with a client error. Your handler never ran.
Mismatched extraction types cause 400 errors:
A common beginner mistake is to define a route that captures an ID and then write the handler with Path<u64>, but later send a non-numeric value. This does not produce a server error; it produces a 400 Bad Request response to the client. If you want to handle invalid IDs gracefully yourself, extract as Path<String> and parse manually, or implement a custom extractor.
Parameter Names and Their Role
The name you give the parameter inside the route pattern is just a label. For a single parameter, and for several parameters extracted as a tuple, values are handed to the handler by position, so the label does not have to match the variable name. The name only becomes load-bearing when you extract into a struct, where each field is matched to a placeholder by name. The following two examples are equivalent in behavior:
// Route parameter name is "id", handler variable is "user_id"
async fn show_user(Path(user_id): Path<String>) -> String {
user_id
}
let app = Router::new().route("/users/{id}", get(show_user));
// Route parameter name is "identifier", handler variable is also "identifier"
async fn show_user(Path(identifier): Path<String>) -> String {
identifier
}
let app = Router::new().route("/users/{identifier}", get(show_user));
In the first example, Axum sees only one dynamic segment, so it places the captured value into the single field of the Path tuple. The label id in the route pattern is not tied to the function's parameter name user_id. In the second example, the names happen to be the same. For more than one parameter, you align tuple positions or use a struct with matching field names.
It is good practice to keep the route parameter name descriptive, like id, user_id, or product_id, because it appears in documentation and sometimes in generated OpenAPI specifications. Avoid names that conflict with Rust keywords. A hyphenated name such as user-id does register and capture normally, but it cannot be a Rust identifier, so it cannot be used as a struct field name - stick to valid Rust identifiers such as user_id or id to keep your code clear.
What Matches and What Does Not
A single dynamic segment matches exactly one non-empty path segment. This means:
/users/42matches/users/{id}and captures"42"./users/does not match, because there is no second segment after the trailing slash./users/42/profiledoes not match, because the pattern expects exactly two segments and the URL has three./users/42/also does not match for the same reason - the trailing slash creates an empty third segment.
If you need to match an empty value or multiple segments, you need a different syntax called a wildcard or catch-all. For a single ID at the end of a path, the simple dynamic segment is perfect.
Here is a small mental model to help you remember: think of {id} as a placeholder that says "one segment goes here, and I will tell you later what that segment was." It cannot match zero segments, and it cannot absorb a slash.
Using the Captured Value in a Response
Often you want to respond with something more useful than a plain string. You can build JSON responses, query a database, or return an HTML page. The captured value is available as a normal Rust variable, so you can use it anywhere inside the handler.
The next example shows a handler that returns a JSON object with the user ID and a fictional name. This requires adding serde and serde_json to your dependencies, but the focus here is on using the captured value.
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
use axum::{routing::get, Router, extract::Path, Json};
use serde::Serialize;
#[derive(Serialize)]
struct UserResponse {
id: u64,
name: String,
}
async fn get_user(Path(user_id): Path<u64>) -> Json<UserResponse> {
Json(UserResponse {
id: user_id,
name: format!("User {}", user_id),
})
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(get_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
When you request http://127.0.0.1:3000/users/7, the server responds with:
{"id":7,"name":"User 7"}
The Path<u64> extractor captured the segment, parsed it into a u64, and passed it to the handler as user_id. The handler then built a UserResponse struct and wrapped it in Json, which Axum automatically converts into an HTTP response with Content-Type: application/json.
Common Mistakes When Writing the Route Pattern
Several small errors can make your route not work as expected. Here are the most frequent ones and how to avoid them.
Forgetting the Braces
If you write .route("/users/id", get(handler)) instead of /users/{id}, then id is a literal static segment. The route will only match the exact URL /users/id and nothing else. No dynamic capture occurs, and a Path extractor in your handler will fail at runtime - the request is rejected with a 500 Internal Server Error ("Wrong number of path arguments"), because the route provides no captured values. Writing /users/:id is worse: it panics at registration, before the server even starts.
Mixing the Two Syntaxes
Do not write :param in a route string on Axum 0.8 at all. A route like /users/:id/{name} panics at registration because of the :id segment. In Axum 0.8+, use braces everywhere: /users/{id}/{name}.
Using a Name That Conflicts with Rust Syntax
The parameter name in the route string is not a Rust variable, so a hyphenated name like user-id does register. But that name cannot appear as a field in a Rust struct, and it reads oddly next to Rust code. Stick to valid Rust identifiers such as user_id or id to keep your code clear.
Assuming the Segment Can Be Empty
A route like /users/{id} will not match /users/. If you need to handle the case where the ID might be missing, add a separate static route for /users that serves the collection, or use an optional parameter pattern. This is a frequent source of confusion for beginners.
A missing segment is a 404, not an empty value:
A request to /users/ never reaches a handler on /users/{id} - there is no captured value at all, so there is nothing to extract. If your handler seems to receive an empty ID, the route that matched is a different one. Register /users separately if the bare path must work.
Path segments are always URL-decoded:
When Axum captures a segment, it automatically decodes percent-encoding. For example, a request to /users/john%20doe will extract "john doe" as the value, not "john%20doe". This is handled by the framework and you do not need to do any manual decoding.
A Step-by-Step Walkthrough for Setting Up Your First Dynamic Route
If you are new to Axum and want to follow along from a blank project, here is a precise sequence of commands and code changes.
Step 1: Create a new Rust project
Open your terminal and run:
cargo new axum-dynamic-route
cd axum-dynamic-route
Step 2: Add Axum and Tokio dependencies
Edit Cargo.toml and add the following under [dependencies]:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
If you are using an older version of Axum (0.7 or earlier), replace axum = "0.8" with axum = "0.7" and use the colon syntax in step 4.
Step 3: Replace src/main.rs with the full example
Open src/main.rs and replace its contents with the code from the earlier minimal example that uses {id} syntax:
use axum::{routing::get, Router, extract::Path};
async fn show_user(Path(user_id): Path<String>) -> String {
format!("You asked for user: {}", user_id)
}
#[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();
}
Step 4: Run the server and test it
Start the server with:
cargo run
In another terminal, send a request:
curl http://127.0.0.1:3000/users/123
You should see the response You asked for user: 123. Try other values like /users/abc to confirm the route is dynamic.
Your dynamic route is working:
If you see the correct response for different IDs, you have successfully set up a route with a path parameter. This is the foundation for building RESTful APIs where resources are addressed by their IDs.
How This Syntax Appears in Real Projects
In production Rust APIs built with Axum, the /users/{id} pattern is one of the most common routes you will encounter. It is used for endpoints that fetch a single resource, update it, or delete it. For example, a typical REST API might have these routes:
GET /users/{id}- retrieve one userPUT /users/{id}- replace an existing userDELETE /users/{id}- remove a user
All three share the same path pattern but use different HTTP methods. You can chain method handlers on a single route definition in Axum, as shown here:
use axum::{routing::{get, put, delete}, Router, extract::Path};
async fn get_user(Path(id): Path<u64>) -> String {
format!("Get user {}", id)
}
async fn update_user(Path(id): Path<u64>) -> String {
format!("Update user {}", id)
}
async fn delete_user(Path(id): Path<u64>) -> String {
format!("Delete user {}", id)
}
let app = Router::new()
.route("/users/{id}", get(get_user).put(update_user).delete(delete_user));
This single route now responds to three different methods on the same URL pattern. The dynamic segment {id} is captured identically for all methods, and each handler receives the value through its own Path extractor.
The colon syntax was the same thing in older Axum versions. If you are reading code written for Axum 0.7, you might see .route("/users/:id", get(get_user).put(update_user).delete(delete_user)). In 0.7 that behaved exactly like the brace version does in 0.8 - but the same code panics on Axum 0.8.
When Not to Use a Dynamic Segment
Although dynamic segments are powerful, they are not always the right tool. Use them only when the variable part of the URL represents a single entity identifier or a similarly indivisible value. Here are situations where a different approach is better:
- A fixed set of words: If the path segment can only be one of a few known values (like
activeorinactive), consider using separate static routes for each value. This often gives better documentation and allows each handler to be simpler. - Multiple segments or slashes: If you need to capture everything after a prefix, including slashes, use a wildcard catch-all pattern instead of a single segment parameter.
- Query string data: If the value is not part of the resource identity but an optional filter, put it in the query string (e.g.,
/users?role=admin) rather than in the path. Path parameters are meant for identifying a specific resource, not for filtering collections.
A dynamic segment like {id} is ideal for patterns such as /users/{id}, /products/{product_id}, or /orders/{order_id}, where the last part uniquely identifies an item.
Summary
The /users/{id} syntax is the way Axum lets a single route pattern match many different URLs by capturing a single dynamic segment. You write the route string with a placeholder, and then use the Path extractor in your handler to receive the captured value. Axum handles parsing, decoding, and type conversion, so you can focus on building your application logic.
The most important takeaway is that the placeholder name is arbitrary, the segment must be non-empty, and the extractor type determines whether invalid values cause an error. With this pattern, you can build RESTful endpoints that address individual resources cleanly and consistently.