Brace Param Syntax in Axum

Learn how to define dynamic path parameters with braces like {id} in Axum routes, extract them safely, and avoid common beginner mistakes.

When you build a web server, you often need to handle URLs that contain changing parts. For example, a user profile page might have URLs like /users/1, /users/42, or /users/999. The number changes, but the pattern stays the same: /users/ followed by some identifier. Axum lets you express that pattern directly in your route definition by placing a brace param inside the path string: /users/{id}.

The braces { and } mark a dynamic segment of the path. In the route /users/{id}, the {id} part acts as a placeholder that matches any single segment of the URL (anything that does not contain a slash). Axum captures whatever text appears in that position and makes it available to your handler function. This feature exists because hardcoding every possible URL is impossible for real-world applications - you need a way to say "this part of the URL can vary."

Changed in Axum 0.8:

Axum versions before 0.8 used a colon (:id) instead of braces ({id}). If you see older code examples with /users/:id, that syntax no longer works in Axum 0.8 or newer. This page covers only the modern brace syntax.

A Basic Route with One Brace Param

Let's start with the smallest possible example: a route that responds to any URL matching /users/{id} and returns the captured value as plain text.

First, make sure your Cargo.toml includes the necessary dependencies:

Cargo.toml
[package]
name = "brace-param-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1", features = ["full"] }

Now write the full server code in src/main.rs:

src/main.rs
use axum::{
    extract::Path,
    routing::get,
    Router,
};
#[tokio::main]
async fn main() {
    // Build the router with a dynamic route
    let app = Router::new()
        .route("/users/{id}", get(show_user_id));
    // Start the server
    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();
}
// Handler that receives the extracted id
async fn show_user_id(Path(id): Path<String>) -> String {
    format!("You requested user with id: {}", id)
}

When you run this program and visit http://127.0.0.1:3000/users/hello, the response body will be You requested user with id: hello. The route pattern /users/{id} matches any single segment after /users/. The actual text hello is extracted and passed to the handler.

The handler signature is the key piece here. The parameter Path(id): Path<String> tells Axum:

  • Path is an extractor - a type that knows how to pull information from the incoming HTTP request. In this case, it pulls the dynamic segments from the URL path.
  • Inside the parentheses, id is the local variable name you will use in the handler body.
  • The type Path<String> says "I expect the captured value to be a String." Axum will automatically parse the raw URL text into a String (which always succeeds because any text is a valid string).

If the URL does not match the pattern - for example, http://127.0.0.1:3000/users/ or http://127.0.0.1:3000/users/1/2 - Axum will respond with a 404 Not Found because the path doesn't have exactly one segment after /users/.

Why Braces Instead of Colons?

Older versions of Axum used a colon to mark dynamic segments: /users/:id. The change to braces in Axum 0.8 happened to align with common conventions seen in OpenAPI specifications and other web frameworks. The brace style also feels more natural to Rust developers because it resembles the format! macro syntax like format!("Hello, {name}").

Practically, the difference is only in how you write the route string. Everything else - how you extract the parameter - remains the same. If you are starting a new project with Axum 0.8 or later, use braces. If you are maintaining an old project, you will eventually need to migrate, but that process is straightforward: replace every :param with {param}.

Extracting a Numeric Parameter

In the first example, we extracted the parameter as a String, which is always safe. But often you need the parameter to be a number so you can query a database or perform arithmetic. Axum can automatically parse the captured text into any type that implements serde::Deserialize. Most primitive types like u32, i64, bool, and char already implement Deserialize, so this works the same way you would expect for numbers - but note it is Deserialize, not FromStr: a custom type that only implements FromStr will not compile as a Path target.

Here is an updated handler that extracts the id as a u64:

src/main.rs
use axum::{extract::Path, routing::get, Router};
async fn show_user_id(Path(id): Path<u64>) -> String {
    format!("User ID (numeric): {}", id)
}

With this handler, visiting /users/42 returns User ID (numeric): 42. The raw string "42" is parsed into the number 42.

But what happens if someone visits /users/abc? The string "abc" cannot be parsed into a u64. In that case, Axum automatically returns a 400 Bad Request response with an error message in the body. You do not need to write any custom error handling - the Path extractor handles the failed parse and rejects the request with a client error. This is a major convenience because it prevents invalid input from reaching your business logic.

The Parse Error Is Not a 404:

A common beginner mistake is to expect /users/abc to return 404 because "no user with that ID exists." Axum distinguishes between two failure modes:

  1. Route mismatch - the path does not match the pattern (e.g., /users/ or /users/1/2) results in 404.
  2. Extraction failure - the path matches the pattern but the parameter cannot be converted to the requested type (e.g., abc for u64) results in 400. Keep this distinction in mind when debugging client errors.

Extracting Multiple Brace Params

Real-world routes often need more than one dynamic segment. For example, a blog might have URLs like /posts/{post_id}/comments/{comment_id} where both parts change. Axum supports any number of brace params in a single route.

Using a Tuple for Multiple Params

The simplest way to extract multiple parameters is to use a tuple in the Path extractor. The tuple's order must match the order the params appear in the route string from left to right.

src/main.rs
use axum::{extract::Path, routing::get, Router};
async fn get_comment(
    Path((post_id, comment_id)): Path<(u64, u64)>,
) -> String {
    format!(
        "Post ID: {}, Comment ID: {}",
        post_id, comment_id
    )
}
// In the router:
let app = Router::new()
    .route(
        "/posts/{post_id}/comments/{comment_id}",
        get(get_comment),
    );

The handler receives a tuple (u64, u64). Axum parses the first dynamic segment (post_id) as the first tuple element and the second segment (comment_id) as the second element. If either fails to parse as u64, the entire request is rejected with a 400.

This approach works well when you have only a few parameters and their order in the URL is obvious. However, if you have many parameters or you want more descriptive variable names, a tuple can become confusing.

Using a Struct with Deserialize

A more readable alternative is to define a custom struct that derives serde::Deserialize and uses named fields that match the brace placeholders in the route string. This requires adding serde as a dependency.

First, update Cargo.toml:

Cargo.toml
[dependencies]
axum = "0.8.9"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

Then define the struct and use it in the handler:

src/main.rs
use axum::{extract::Path, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct CommentParams {
    post_id: u64,
    comment_id: u64,
}
async fn get_comment(
    Path(params): Path<CommentParams>,
) -> String {
    format!(
        "Post ID: {}, Comment ID: {}",
        params.post_id, params.comment_id
    )
}

The field names post_id and comment_id must match exactly the names inside the braces in the route string. Axum uses these names to match each captured segment to the right field, regardless of their order in the struct. This is safer when you have many parameters because the names make the mapping explicit - but note the check happens at runtime, not compile time: if a struct field has no matching placeholder, requests fail with a 400 response, so the compiler will not catch a typo for you.

Structs Improve Readability:

For any route with more than two dynamic segments, prefer a named struct over a tuple. The code becomes self-documenting, and adding or reordering parameters later is less error-prone. The only extra cost is deriving Deserialize and adding serde to your project.

Combining Brace Params with Other Extractors

A handler can accept more than just the Path extractor. Axum allows you to mix Path with other extractors like Query, State, or Json, as long as you follow one rule: at most one extractor that consumes the request body can be present. By convention that body extractor goes last in the parameter list, after the extractors that read from the URL or the request parts.

The Path extractor reads from the URL, not the body, so it can appear anywhere in the parameter list. Here is a handler that extracts a path param, a query parameter, and a JSON body all at once:

src/main.rs
use axum::{extract::{Path, Query, Json}, routing::post, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
}
#[derive(Deserialize)]
struct UpdateUser {
    name: String,
}
async fn update_user(
    Path(id): Path<u64>,
    Query(pagination): Query<Pagination>,
    Json(body): Json<UpdateUser>,
) -> String {
    let page = pagination.page.unwrap_or(1);
    format!(
        "Updating user {} on page {} with new name {}",
        id, page, body.name
    )
}
// Route: POST /users/{id}?page=2 with JSON body {"name":"Alice"}

The order Path, Query, Json is fine because only Json consumes the body. If you tried to put Json before Path, it would still work because Path doesn't consume the body, but it's convention to put body-consuming extractors last. However, if you had two body-consuming extractors (like Json and Form), the handler would fail to compile with a clear error.

Dynamic Segments in the Middle of a Path

A common misconception is that a brace param must be the last segment of the URL. That is not true - a dynamic segment can appear anywhere, as long as each segment is separated by a slash. For example, the route /users/{id}/profile is valid and matches URLs like /users/7/profile.

src/main.rs
use axum::{extract::Path, routing::get, Router};
async fn show_profile(Path(id): Path<u64>) -> String {
    format!("Profile page for user {}", id)
}
let app = Router::new()
    .route("/users/{id}/profile", get(show_profile));

In this case, Axum matches the first part users, then captures any single segment as id, then requires the literal segment profile. If you visit /users/7/settings, you get a 404 because the final segment doesn't match.

This feature is useful when you have sub-resources under a dynamic parent. You might later define /users/{id}/posts to list a user's posts, and /users/{id}/profile to show the profile.

Wildcard Params Must Be Last:

While a regular brace param like {id} can appear in the middle, a catch-all wildcard param written as {*rest} must always be the last segment because it matches everything including slashes. Do not confuse the two: {id} matches exactly one segment, {*rest} matches one or more segments (it does not match an empty remainder). The wildcard syntax has its own dedicated page; for now, remember that {id} is safe to use anywhere.

Common Mistakes and How to Fix Them

Several pitfalls frequently trip up beginners when using brace params. Being aware of them early will save you hours of debugging.

Mismatched Placeholder and Extractor Field

If you use a struct to extract params, every field in the struct must correspond to a brace placeholder in the route, and vice versa. Consider this incorrect code:

src/main.rs
use axum::{extract::Path, routing::get, Router};
use serde::Deserialize;
// Route: /users/{id}
#[derive(Deserialize)]
struct Params {
    user_id: u64,
}
async fn handler(Path(params): Path<Params>) {}

The route has {id}, but the struct field is user_id. Axum will look for a placeholder named user_id and not find it. At runtime, any request to /users/123 will result in a 400 Bad Request because the extractor fails with a missing field. The fix is to name the struct field exactly the same as the placeholder: id: u64.

Using the Old Colon Syntax

If you copy code from an older tutorial, you might see /users/:id. In Axum 0.8+, this syntax is invalid: registering such a route panics immediately at startup with Path segments must not start with ':'. For capture groups, use '{capture}'. It is not treated as a literal and does not silently fail to match - the application crashes on startup. If your dynamic route isn't working and you see the colon in your route string, replace it with braces.

Expecting Optional Params

A brace param is always required. The route /users/{id} will not match /users/ or /users. If you need an optional segment, you must define two separate routes: one with the param and one without. Axum does not support optional path parameters directly.

Forgetting to Add serde for Struct Extraction

If you derive Deserialize on a struct for path extraction, you must include serde with the derive feature in your dependencies. Without it, the code will not compile. The error message will mention Deserialize not being in scope, which is your clue to add serde.

Using the Wrong Type for the Parameter

When you write Path<u64>, Axum will reject any request where the segment is not a valid unsigned 64-bit integer. This is usually what you want, but sometimes you need to accept strings that look like numbers but may contain leading zeros or other characters. In that case, extract as String and parse manually inside the handler, where you can handle errors gracefully. For example, user IDs from some systems might be alphanumeric; extracting as u64 would incorrectly reject abc123.

Full Working Example: A Mini User API

Let's put everything together into a complete server that demonstrates multiple brace params, a struct extractor, and type parsing. This example will have two routes:

  • GET /users/{id} - returns a simple message with the numeric ID.
  • GET /posts/{post_id}/comments/{comment_id} - returns both IDs using a struct.

Create a new project with the following files.

Cargo.toml:

Cargo.toml
[package]
name = "brace-param-full-example"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

src/main.rs:

src/main.rs
use axum::{
    extract::Path,
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CommentParams {
    post_id: u64,
    comment_id: u64,
}
async fn show_user(Path(id): Path<u64>) -> String {
    format!("User ID: {}", id)
}
async fn show_comment(
    Path(params): Path<CommentParams>,
) -> String {
    format!(
        "Post {} has comment {}",
        params.post_id, params.comment_id
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{id}", get(show_user))
        .route(
            "/posts/{post_id}/comments/{comment_id}",
            get(show_comment),
        );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run the server with cargo run, then test with curl:

curl http://127.0.0.1:3000/users/123
# Output: User ID: 123
curl http://127.0.0.1:3000/posts/5/comments/9
# Output: Post 5 has comment 9
curl http://127.0.0.1:3000/users/not-a-number
# Output: 400 Bad Request (body contains parse error)

The last request demonstrates the automatic 400 response when the parameter cannot be converted to u64. This is the expected behavior, and it prevents invalid data from ever reaching your application logic.

Summary

Brace param syntax is the modern way to define dynamic URL segments in Axum. Place {name} inside a route path to capture a variable segment, then use the Path extractor in the handler to retrieve the captured value. The extractor can convert the raw text into any type that implements serde::Deserialize, giving you type safety without manual parsing. For multiple parameters, you can use a tuple for simple cases or a serde::Deserialize struct for readability. A failed conversion results in a 400 response, while a route that doesn't match at all returns a 404. Axum 0.8 switched from colon syntax to brace syntax, so always use {id} - never :id - in new code.

Mastering brace params is the foundation for building any REST API with Axum. Once you understand how dynamic segments work, you can move on to more advanced routing patterns like catch-all wildcards and route nesting, all of which build on the same Path extractor and route matching principles.