Path Tuple Parameters

Extract multiple path parameters from a single URL into a Rust tuple inside Axum handlers with clear examples and common mistakes

When a route needs more than one value from the URL, Axum lets you grab all of them in one go by using a tuple as the type inside the Path extractor. A single segment uses Path<T> with one type; here we extend that idea to several segments at once, with one type per segment inside a tuple.

Starting with two numbers

A URL like /users/42/posts/7 contains two identifiers: the user ID 42 and the post ID 7. Your route pattern must have two placeholders, one for each value. In Axum 0.8 and later, placeholders are written with curly braces: {user_id} and {post_id}.

The simplest way to capture both is to use Path with a tuple of two types that match what you expect. For numeric IDs, that might be (u64, u64).

use axum::{extract::Path, routing::get, Router};
async fn get_user_post(Path((user_id, post_id)): Path<(u64, u64)>) -> 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_user_post));
    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();
}

Notice the handler parameter: Path((user_id, post_id)): Path<(u64, u64)>. The outer Path is the extractor. Inside it, the pattern (user_id, post_id) destructures the tuple into two separate variables. The type annotation says the tuple is (u64, u64).

When a request comes to /users/42/posts/7, Axum matches the route, extracts the two segments 42 and 7 as strings, parses each one into u64, and constructs a tuple (42, 7). Then the handler receives that tuple, and the destructuring pattern binds user_id to 42 and post_id to 7.

If you run this and request that URL, you will see User 42 requested post 7 in the response body.

It works when the segments are valid numbers:

If both placeholders contain strings that parse successfully into u64, the handler runs and you get your formatted response. This is the happy path.

Why tuples are useful

Axum's Path extractor can accept any type that implements the Deserialize trait from Serde. A tuple like (u64, u64) implements Deserialize when every element does. That means you can collect several path parameters without defining a new struct. For two or three parameters, a tuple keeps the code short and readable. For many parameters, a struct with named fields may be clearer.

The main advantage is conciseness. You don't need to create a separate type, derive traits, or name each field twice. The tuple order directly matches the route pattern order.

Order matters more than names

The route placeholders can have any names, but the tuple elements receive values in the exact order the placeholders appear in the route string. Suppose you write:

.route("/products/{category}/{item}", get(show_product))

and the handler:

async fn show_product(Path((category, item)): Path<(String, String)>) -> String {
    format!("Category: {}, Item: {}", category, item)
}

The first placeholder {category} becomes the first tuple element, the second {item} becomes the second. The names category and item in the destructuring are just local variable names; they don't need to match the placeholder names. You could name them a and b and still get the same values in the same order.

This becomes important when you accidentally swap the order in the tuple type versus the route. For example:

// Route: /users/{user_id}/posts/{post_id}
// Handler uses (post_id, user_id) but type is still (u64, u64)
async fn get_user_post(Path((post_id, user_id)): Path<(u64, u64)>) -> String {
    // post_id gets 42, user_id gets 7
    format!("Post {} User {}", post_id, user_id)
}

This compiles and runs, but the values are swapped. There is no compile-time check that your variable names align with the route placeholders. Only the order of the types in the tuple matters.

Tuple order is positional, not named:

Always keep the tuple element order exactly matching the order of {placeholders} in the route. If you mix up the order, you will get correct-looking code that does the wrong thing at runtime.

Mixing different types

You are not limited to two numbers. Each element can be a different type, as long as that type implements Deserialize. Common types like u32, i64, String, bool, and char all work out of the box.

Consider a route like /orders/{order_id}/items/{sku} where the first is a number and the second is a string.

use axum::{extract::Path, routing::get, Router};
async fn get_order_item(Path((order_id, sku)): Path<(u64, String)>) -> String {
    format!("Order {} has item with SKU {}", order_id, sku)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/orders/{order_id}/items/{sku}", get(get_order_item));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

If a request goes to /orders/100/items/ABC-123, Axum parses 100 into u64 and leaves ABC-123 as a String. The handler receives (100, "ABC-123").

This works because String implements Deserialize directly from a string segment, and u64 implements it through its FromStr conversion. If a segment can't be parsed into the expected type, the extraction fails and Axum returns an error response automatically.

More than two parameters

Tuples can have three, four, or even more elements, up to sixteen: that is how far Serde's Deserialize support for tuples goes, so a seventeen-element tuple does not compile. The route pattern must have the same number of placeholders.

For example, a route that identifies a resource across three levels:

async fn get_file(
    Path((org, project, file_id)): Path<(String, String, u32)>
) -> String {
    format!("Org: {}, Project: {}, File ID: {}", org, project, file_id)
}
// Route: /orgs/{org}/projects/{project}/files/{file_id}

Place that handler on a route with three placeholders:

let app = Router::new()
    .route(
        "/orgs/{org}/projects/{project}/files/{file_id}",
        get(get_file),
    );

Every placeholder must appear in the URL; if any segment is missing or extra segments exist, the route will not match. The extraction only happens after a successful route match.

Destructuring the tuple inside the handler

The pattern we used so far destructures the tuple directly in the function parameter. That is the most common style because it is concise. But you can also receive the whole tuple as one variable and then access elements by index.

async fn get_user_post(path: Path<(u64, u64)>) -> String {
    let (user_id, post_id) = path.0;
    format!("User {} requested post {}", user_id, post_id)
}

Here path is of type Path<(u64, u64)>. The Path struct has a single public field 0 that holds the inner value. In this example, path.0 is the tuple (u64, u64). You can then destructure it or use .0 and .1 to get individual elements.

async fn get_user_post(path: Path<(u64, u64)>) -> String {
    let user_id = path.0.0;
    let post_id = path.0.1;
    format!("User {} requested post {}", user_id, post_id)
}

Both approaches work. The first one (destructuring in the parameter) is preferred because it immediately gives you named variables. The second is useful if you need to pass the tuple or the Path object somewhere else.

What happens when extraction fails

Axum uses the Deserialize trait to convert each path segment into the expected type. If any segment cannot be converted, the Path extractor rejects the request. The rejection type is axum::extract::rejection::PathRejection, which implements IntoResponse. That means Axum automatically turns the rejection into an HTTP response, usually with status 400 Bad Request and a body describing the problem.

For example, if your handler expects (u64, u64) and the URL is /users/abc/posts/7, the first segment abc cannot be parsed into u64. Axum will not call your handler. Instead, it sends a 400 Bad Request response with body Invalid URL: Cannot parse value at index 0 with value `abc` to a `u64` .

You can test this by starting the server and making a bad request.

Extraction failure stops the handler:

If any element of the tuple fails to parse, the whole Path extraction fails. Your handler never runs. This is different from some other frameworks where you might get None or an empty value.

Handling rejection manually with Result

Sometimes you want to customize what happens when path parsing fails. You can change the handler return type to Result<T, PathRejection> and then handle the error case yourself.

use axum::extract::rejection::PathRejection;
use axum::extract::Path;
use axum::http::StatusCode;
async fn get_user_post(
    path: Result<Path<(u64, u64)>, PathRejection>,
) -> Result<String, (StatusCode, String)> {
    match path {
        Ok(Path((user_id, post_id))) => {
            Ok(format!("User {} requested post {}", user_id, post_id))
        }
        Err(rejection) => {
            // You can inspect the rejection and return a custom error
            Err((
                StatusCode::BAD_REQUEST,
                format!("Invalid path parameters: {}", rejection.body_text()),
            ))
        }
    }
}

The rejection.body_text() method returns a human-readable string explaining what went wrong. You can then include that in your own error response or log it.

This gives you control, but for most applications the automatic 400 Bad Request is fine.

A practical example with posts and comments

Imagine you are building an API for a blog. You have posts and each post has comments. The URL /posts/{post_id}/comments/{comment_id} identifies a single comment on a post.

Here is a complete handler that extracts both IDs as u64 and returns a simple confirmation.

use axum::{extract::Path, routing::get, Router};
async fn get_comment(
    Path((post_id, comment_id)): Path<(u64, u64)>
) -> String {
    format!("Fetching comment {} for post {}", comment_id, post_id)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/posts/{post_id}/comments/{comment_id}", get(get_comment));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /posts/10/comments/5 returns Fetching comment 5 for post 10.

If you later decide that post IDs should be strings because they might be slugs, you can change the tuple type to (String, u64) and Axum will accept /posts/hello-world/comments/5 without any other changes.

Using a tuple inside a larger extractor set

You can combine Path tuple with other extractors like Query or State. The same rule applies: the path tuple is one extractor, and body-consuming extractors must be last if any are present.

use axum::extract::{Path, Query, State};
use serde::Deserialize;
use std::sync::Arc;
struct Database;
#[derive(Clone)]
struct AppState {
    db: Arc<Database>,
}
#[derive(Deserialize)]
struct Pagination {
    page: u32,
}
async fn list_comments(
    State(state): State<AppState>,
    Path((post_id, comment_id)): Path<(u64, u64)>,
    Query(pagination): Query<Pagination>,
) -> String {
    // Use state, post_id, comment_id, pagination...
    let _ = &state.db;
    format!(
        "Post {} comment {} page {}",
        post_id, comment_id, pagination.page
    )
}

The order of non-body extractors does not matter, but State often comes first by convention. Body extractors (like Json) must be last. Since Path is not body-consuming, it can appear anywhere among the non-body extractors.

Common beginner mistakes

Wrong number of placeholders

If your handler expects a tuple of length 2 but the route only has one placeholder, the route still matches, but extraction fails: Axum returns a 500 Internal Server Error with body Wrong number of path arguments for `Path`. Expected 2 but got 1 . A wrong number of parameters is treated as a mistake in the handler signature, not a client error, so it is a 500 rather than a 404 or a 400. Similarly, if the route has three placeholders but the tuple has only two elements, extraction fails with a 500.

// Route has one placeholder but handler expects two:
// requests to /users/42 match the route, then fail extraction with a 500
.route("/users/{id}", get(get_user_post))

There is no automatic filling with zero or default values. The number must match exactly.

Type mismatch

If you expect u64 but the segment contains letters, extraction fails with 400 Bad Request. This is often surprising when a user types a word instead of a number in the URL.

Forgetting the Path wrapper

You cannot use a bare tuple as an extractor. The handler parameter must be Path<(u64, u64)>, not (u64, u64). The Path extractor tells Axum to read from the URL path. Without it, the compiler will complain about missing trait implementations.

Using String for everything

You can use String for every element and then parse later, but that moves the parsing logic into your handler. It's usually better to let Axum do the parsing for you by specifying the concrete types in the tuple.

Assuming placeholder names affect tuple order

As already emphasized, the names inside {} are just for documentation and pattern matching; they don't change the order of values. Only the order in the route string and the tuple type order matter.

When tuples become messy

A tuple of two or three elements is easy to read. A tuple of five or more starts to become unclear because you must remember the meaning of each position. In that case, consider defining a struct with named fields that derives Deserialize. For this page, stick to tuples when the number of parameters is small and the meaning is obvious from context.

One element still needs a tuple:

A single segment can be written as Path<(u32,)>, with a trailing comma, which is a one-element tuple. Without the comma, (u32) is just u32 in parentheses, not a tuple, so it means the same as Path<u32>. The trailing comma is what makes it a tuple.

A quick summary of how it all works

When a request arrives, Axum matches the URL against the route patterns. Once a route matches, it knows which parts of the URL correspond to the placeholders. For each placeholder, it extracts the raw string from the URL segment. Then it tries to parse that string into the expected type for each element of the tuple. If all parsing succeeds, the tuple is constructed and passed to your handler. If any parsing fails, the Path extractor rejects the request and returns a 400 Bad Request by default.

The tuple type's elements define what types you want. The route pattern defines how many placeholders and in what order they appear. The two must align exactly.

What you should remember

  • Use Path<(Type1, Type2, ...)> to extract multiple path parameters.
  • The number of placeholders in the route must equal the number of elements in the tuple.
  • The order of placeholders determines the order of tuple elements, not the placeholder names.
  • Each element type must implement Deserialize. Most primitive types do.
  • If extraction fails, the handler is not called, and Axum sends a 400 Bad Request by default.
  • You can handle failures manually by taking Result<Path<(...)>, PathRejection> as a handler parameter.
  • For a small number of parameters, tuples are concise and readable. For many, a struct may be better.

This page focused solely on tuple parameters. With this knowledge, you can now build routes that depend on multiple identifiers from the URL without writing custom parsing code. Next, you might want to learn about extracting path parameters into a struct, which gives named fields and better readability for routes with more parameters.