Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Routers and Handlers

Axum Path Parameters, Captures and Wildcards

Capture URL segments in Axum 0.8 with {id} and {*rest}, extract them as numbers, tuples or structs with Path, understand match priority, and handle parse failures.

Real APIs rarely use fixed URLs. /users/42, /posts/2025/rust-tips, /files/images/logo.png: part of the path is data. Axum calls these parts captures. You mark them in the route pattern, and the Path extractor hands them to your handler already parsed into the types you asked for.

This lesson covers the capture syntax (which changed in Axum 0.8, so watch out for old tutorials), the three ways to receive captures, how overlapping patterns are prioritised and what clients see when a capture cannot be parsed.

Capture syntax

In Axum 0.8 and later, a capture is a name in curly braces:

Rust
use axum::{extract::Path, routing::get, Router};

async fn user(Path(id): Path<u32>) -> String {
    format!("user #{id}")
}

fn app() -> Router {
    Router::new().route("/users/{id}", get(user))
}

Older versions (0.7 and before) used a colon: /users/:id. If a tutorial shows :id or *path, it targets an old version; in 0.8 those are plain literal text and is the capture. To match a literal brace, double it: {{ and }}.

A capture matches one whole segment: /users/{id} matches /users/42 but not /users/42/posts and not /users/. Segments are percent-decoded before they reach you, so /search/caf%C3%A9 gives "cafรฉ".

Several captures

Rust
async fn post(Path((year, slug)): Path<(u16, String)>) -> String {
    format!("{year}: {slug}")
}

// Router::new().route("/posts/{year}/{slug}", get(post))

A tuple receives the captures in order of appearance. A struct receives them by name, which is safer once there are more than two:

Rust
use serde::Deserialize;

#[derive(Deserialize)]
struct PostPath {
    year: u16,
    slug: String,
}

async fn post(Path(p): Path<PostPath>) -> String {
    format!("{}: {}", p.year, p.slug)
}

For a single capture you can use any type that implements Deserialize from a string: u32, String, uuid::Uuid, a chrono date, even an enum.

Wildcards

A wildcard capture matches the rest of the path, including slashes. It is written {*name} and must be the last part of the pattern:

Rust
async fn serve_file(Path(path): Path<String>) -> String {
    format!("would serve: {path}")
}

// Router::new().route("/files/{*path}", get(serve_file))
// GET /files/images/logo.png  ->  path = "images/logo.png"

Wildcards need at least one character, so /files/ does not match /files/{*path}. Treat the value as untrusted: never join it to a directory without checking for ... Prefer tower-http's ServeDir, which does this correctly.

What if parsing fails?

If /users/abc reaches Path<u32>, deserialisation fails and Axum answers 400 Bad Request with a plain-text message that mentions the problem, without ever running your handler. Missing captures (a handler asks for Path<u32> on a route with no capture) produce a 500, because that is a programmer mistake, not a client one. Chapter 3's custom extractors and rejections lesson shows how to turn these into your own JSON errors.

Priority: specific beats general

Several patterns can match one URL:

Rust
Router::new()
    .route("/users/me", get(current_user))
    .route("/users/{id}", get(user_by_id))
    .route("/{*rest}", get(catch_all))

GET /users/me goes to current_user, GET /users/7 to user_by_id, everything else to catch_all. Axum (through the matchit router) prefers static segments over captures and captures over wildcards, regardless of the order you wrote them. What it rejects, at start-up, is genuine ambiguity: /users/{id} and /users/{name} are the same shape and conflict.

A runnable model of capture matching

This stand-in implements the matching rules: static beats capture beats wildcard, captures cover exactly one segment, wildcards swallow the rest. It returns the captured values as a map, as a real router would store them for the Path extractor.

Rust Stand-in: match patterns with {id} and {*rest}

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check the output: /users/me picks the static route, /users/42/posts falls to the wildcard because the capture route needs exactly two segments, and /files/ fails the files wildcard and lands on the global one.

Typed extraction: tuples, structs and errors

Path<T> deserialises the captures with serde. The next model shows what that gives you: single values, tuples by position, and a failure that names the problem. It uses FromStr to stand in for serde's string-to-type conversion.

Rust Stand-in: typed path extraction and parse errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Practical advice

  • Name captures after what they mean (, not ), especially when using structs.
  • Validate beyond the type: Path<u32> accepts 0. A product ID of zero may still be "not found" in your logic.
  • Use Path<Uuid> or a newtype with a custom Deserialize for stronger types.
  • Static routes such as /users/me can sit next to /users/{id} without conflict.
  • Prefer query strings for optional filters (/users?role=admin); see Path and Query extractors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pattern captures a user id in Axum 0.8?

    Axum 0.8 switched to curly braces; the colon syntax belongs to 0.7 and earlier.
  2. 2. What does a {*path} wildcard capture?

    A wildcard swallows all remaining segments and must be the last part of the pattern.
  3. 3. Given /users/me and /users/{id}, which handler serves GET /users/me?

    Static segments take priority over captures regardless of registration order.
  4. 4. What does the client get when /users/abc is requested and the handler takes Path<u32>?

    A deserialisation failure becomes a Path rejection, answered with 400 before the handler is called.

Summary

  • Captures are (one segment) and {*name} (rest of the path, last position) in Axum 0.8.
  • Receive them with Path<T> as a single value, a tuple (by position) or a struct (by name).
  • Static segments beat captures, and captures beat wildcards, independent of route order.
  • Parse failures become a 400 rejection; treat wildcard values as untrusted.

Next: Nesting and Merging Routers