Path extractor rejection

What happens when a path segment cannot be parsed into the type the handler declared and what response Axum returns

A route like /users/{id} promises that the part of the URL where {id} sits holds a user id. The Path extractor is the piece that keeps that promise. It takes the text from that segment of the URL and tries to turn it into the type the handler declared, such as i32. When the text cannot become that type, the extractor rejects the request. Axum answers with status 400 and a plain text body that names the value and the type it could not become.

Where This Fits

The default rejection behavior page showed the general rule: an extractor that fails stops the request before the handler runs, and Axum answers on its own. This page takes the first extractor in that table and looks at it closely. Path is the simplest extractor to reason about, because its input is one short piece of text from the URL, and its failures have exactly one common cause.

The Smallest Working Example

Here is the smallest route that can reject on a path segment. The handler declares Path<i32>, so the segment must be a whole number.

// src/lib.rs
use axum::{extract::Path, routing::get, Router};

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

async fn get_user(Path(id): Path<i32>) -> String {
    format!("User {}", id)
}
// src/main.rs
use axum_project::app;

#[tokio::main]
async fn main() {
    let app = app();
    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();
}

The Cargo.toml file needs these dependencies:

# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Run the server with cargo run. A number in the path works:

curl http://127.0.0.1:3000/users/42
User 42

A word in the path is rejected:

curl http://127.0.0.1:3000/users/abc

The response has status 400 and this body:

Invalid URL: Cannot parse `abc` to a `i32`

Nothing in the handler ran for the second request. There was no i32 to format, so Axum answered before the handler started.

Seeing a Path Rejection:

If /users/42 prints User 42 and /users/abc returns 400 with the text about parsing abc, the Path extractor is working. The rejection is Axum doing its job, not a bug in the route.

What the Path Extractor Does

Path is an extractor, which means it is a type that knows how to pull one part out of a request. Its part is the path parameters, the values captured by the {name} placeholders in the route pattern. When a request arrives for /users/42, the router matches the pattern /users/{id} and stores the text 42 under the name id. The Path<i32> extractor then reads that stored text and parses it into an i32.

Parsing here means the same thing it means anywhere in Rust. The text is fed to the target type's parser, and the parser either produces a value or fails. 42 parses into an i32 without trouble. abc has no meaning as a whole number, so parsing fails. A number too large for an i32 fails too, because the value cannot fit in the type even though every character is a digit.

The route pattern and the handler type work as a pair. The pattern says where the value lives in the URL. The type says what the value must be. A mismatch between the text in the URL and the declared type is the whole story of a Path rejection.

The Rejection Type and Its Default Response

When parsing fails, the extractor produces a PathRejection. That type is an enum, a value that can be one of a few variants, with one variant for each way Path extraction can fail. The variant for a failed parse is called FailedToDeserializePathParams. Its default response is status 400 with the body shown above. The body has a fixed first part, Invalid URL, and then the detail from the failed parse, which names the text and the target type.

Two other facts about this rejection are worth knowing now. First, the response body is plain text with content type text/plain; charset=utf-8, like every default rejection. Second, the handler never runs, so no database lookup or other work happens for a rejected id. That second fact is a small performance win as well as a correctness win: a request that cannot name a real user never touches the data store.

The Fixed Part and the Detail:

The body always starts with Invalid URL. What follows the colon changes with the request, because it quotes the exact segment that failed and the exact type it was supposed to become. Match on the status code and the fixed part when writing client code, never on the full body.

Which Inputs Reject and Which Do Not

The fastest way to learn the boundary is to run several values through the same route. All of these were checked by sending real requests to Axum 0.8.9 with a Path<i32> handler.

Request pathResultWhy
/users/42200, User 4242 parses as an i32
/users/-5200, User -5A negative number is a valid i32
/users/0200, User 0Zero is a valid i32
/users/abc400Letters cannot parse as a number
/users/4.5400A decimal point cannot parse as an i32
/users/99999999999999999999400The digits are fine, but the value is too large for an i32
/users/42abc400Mixed digits and letters cannot parse as a number
/users/404, empty bodyNo segment is present, so no route matches at all
/users404, empty bodyThe route pattern needs a segment after /users/

The negative number row surprises some beginners. A minus sign is part of a number, so -5 is a perfectly good i32, and the handler receives -5 like any other id. Whether a negative id should exist in the database is a different question, one for the handler to answer, not for the extractor. The extractor only checks the shape of the value.

The last two rows are not rejections at all. When the segment is missing entirely, the router finds no route to match, and the response is a 404 with an empty body. A rejection needs a matched route and a present segment that fails to parse. Keep that distinction in mind, because a client that sees a 404 for /users/ and a 400 for /users/abc is seeing two different layers of Axum at work.

Path With More Than One Segment

Real routes often capture more than one segment. A route like /users/{user_id}/posts/{post_id} captures two numbers, and the handler can declare them together. Axum supports a tuple type for this, where each position in the tuple matches one placeholder in the route, in order.

// src/lib.rs
use axum::{extract::Path, routing::get, Router};

pub fn app() -> Router {
    Router::new().route("/users/{user_id}/posts/{post_id}", get(get_post))
}

async fn get_post(Path((user_id, post_id)): Path<(i32, i32)>) -> String {
    format!("Post {} by user {}", post_id, user_id)
}

The pattern Path((user_id, post_id)) pulls the two values out of the tuple in one step. A request to /users/7/posts/3 returns Post 3 by user 7. A request to /users/7/posts/abc is rejected with 400, because the second segment cannot parse as an i32, even though the first one is fine. Its body names the position that failed: Invalid URL: Cannot parse value at index 1 with value abcto ai32``. A request to /users/abc/posts/3 is rejected for the same reason, with index 0 in the detail instead of index 1. Either segment can cause the rejection, and the body names the one that failed.

Tuple Order Follows the Route:

The tuple positions follow the order of the placeholders in the route pattern, not the order of the variable names. Swapping the two names in the pattern while keeping the route the same silently swaps which id is which. Read the route pattern left to right when writing the tuple.

Path With a Struct

A tuple works for two or three segments, but it gets hard to read as routes grow. For routes with several segments, a struct with one named field per placeholder is clearer. The struct needs the Deserialize derive from serde, which teaches serde how to fill the struct in from the captured text.

// src/lib.rs
use axum::{extract::Path, routing::get, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct PostPath {
    user_id: i32,
    post_id: i32,
}

pub fn app() -> Router {
    Router::new().route("/users/{user_id}/posts/{post_id}", get(get_post))
}

async fn get_post(Path(params): Path<PostPath>) -> String {
    format!("Post {} by user {}", params.post_id, params.user_id)
}

Each field name must match a placeholder name in the route. user_id in the struct matches {user_id} in the pattern, and post_id matches {post_id}. If a field name does not match any placeholder, deserialization fails and the request is rejected with 400. If a field has the wrong type for its segment, the same rejection appears, with the field named in the body: a request to /users/7/posts/abc returns Invalid URL: Cannot parse post_idwith valueabcto ai32``. The struct form rejects for exactly the same reasons as the tuple form. It only changes how the values are named inside the handler.

Path With a String Never Rejects on Parsing

Declaring the segment as String changes the picture completely. Every path segment is already text, so there is nothing to parse and nothing that can fail. Path<String> accepts abc, 42, and 4.5 alike, and hands the raw text to the handler.

// src/lib.rs
use axum::{extract::Path, routing::get, Router};

pub fn app() -> Router {
    Router::new().route("/users/{name}", get(get_by_name))
}

async fn get_by_name(Path(name): Path<String>) -> String {
    format!("Looking up user named {}", name)
}

A request to /users/abc now returns 200 with Looking up user named abc. That is the right choice when the segment really is a name or a slug. It is the wrong choice when the segment is meant to be a number, because the handler then has to parse the string itself and decide what to do with a bad value. The type in the handler should match the real meaning of the segment. A numeric id belongs in an i32, a name belongs in a String, and the rejection behavior follows from that choice.

Do Not Parse Inside the Handler to Dodge Rejections:

Reaching for Path<String> and then parsing the string inside the handler only to return the same 400 by hand is wasted work. The extractor already does that parsing, with the same status code and a clearer message. Keep the numeric type on the extractor and let the rejection happen.

The Second Variant, MissingPathParams

PathRejection has a second variant besides the parse failure. It is called MissingPathParams, and its default response is status 500 with the body No paths parameters found for matched route. It fires when Axum's internal store of path parameters is missing for a route that matched, which is an internal problem rather than a client mistake. That is why it gets a 500, the status for server side problems, instead of a 400.

Ordinary handlers never trigger this variant. It comes from Axum's internals, and the usual cause named in the official docs is extracting the whole Request before Path, which takes the path parameters away from the extractor. In Axum 0.8.9 a handler that lists both Request and Path does not even compile as a handler, so this variant is not something a beginner will meet by writing a normal route. It is listed here so the enum makes sense when you read its docs, and so a 500 with that body is recognizable if it ever appears. The parse failure is the variant that matters in daily work.

The Concept Behind Path Rejection

The Path extractor turns a piece of the URL into a typed value. That conversion has to happen somewhere, and doing it in the extractor keeps two promises at once. The handler gets a real i32 it can use without checking, and the client gets a clear error when the URL cannot supply one. A rejection is the extractor keeping the first promise honest by refusing to invent a value.

Think of the route pattern as a form with one blank, and the type as the label on that blank saying a whole number goes here. A visitor who writes letters in the number blank has not filled the form in correctly. The extractor is the person checking the form at the door. It sends the visitor back with a note about the blank, instead of passing a half filled form to the handler and hoping for the best.

Why a 400 and Not a 404

Beginners sometimes expect /users/abc to return 404, on the grounds that no user with the id abc exists. That reading mixes up two different questions. Routing asks whether a URL pattern matches, and /users/{id} does match /users/abc, because any text fits the placeholder. The handler then asks whether a user with that id exists, and that question can only be answered once the id is a number. The 400 says the request itself is malformed, the id is not a number at all. A 404 belongs to the later question, when a well formed numeric id names no user in the data store. The extractor answers the first question, the handler answers the second, and the two status codes stay separate because the two questions are separate.

How the Request Flows Through a Path Rejection

Here is the path a request takes when the segment fails to parse, in plain text:

Client requests /users/abc
        |
        v
Router matches /users/{id} and stores "abc" as id
        |
        v
Path<i32> tries to parse "abc" into an i32
        |
        v
Parsing fails, FailedToDeserializePathParams is produced
        |
        v
Handler is skipped
        |
        v
Rejection becomes a 400 response with plain text body
        |
        v
Client receives the error

The good path differs at the parsing step. When parsing succeeds, the handler runs with the i32 and its return value becomes the response. Everything before that step is the same.

Testing Path Rejection

The test below checks the three outcomes that matter: a good id works, a bad id is rejected with 400, and a missing segment is a 404 from routing. It uses oneshot from the tower crate, which needs to be a dev dependency.

# Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
// tests/path_rejection_test.rs
use axum::{
    body::{to_bytes, Body},
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

async fn get(uri: &str) -> (StatusCode, String) {
    let response = app()
        .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
        .await
        .unwrap();
    let status = response.status();
    let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    (status, String::from_utf8_lossy(&bytes).to_string())
}

#[tokio::test]
async fn good_id_returns_user() {
    let (status, body) = get("/users/42").await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "User 42");
}

#[tokio::test]
async fn bad_id_is_rejected_with_400() {
    let (status, body) = get("/users/abc").await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body, "Invalid URL: Cannot parse `abc` to a `i32`");
}

#[tokio::test]
async fn too_large_id_is_rejected() {
    let (status, _) = get("/users/99999999999999999999").await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn missing_segment_is_404() {
    let (status, _) = get("/users/").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

The helper get sends one request through the router and returns the status and the body as a string. Each test checks one row of the table from earlier in the page. The bad id test asserts the exact body, because the body text is the contract a client reads. Run the tests with cargo test.

Tests That Pin the Behavior:

The exact body assertion in the bad id test is worth keeping. If a future Axum version changes the wording, this test fails loudly instead of letting the docs quietly go stale.

Common Beginner Mistakes

Using the Old Colon Syntax in Routes

// Wrong - panics in Axum 0.8 when the router is built
Router::new().route("/users/:id", get(get_user))

Axum 0.8 uses {id} for placeholders. The old :id form makes the router panic at startup with the message that path segments must not start with :. The panic happens when app() runs, before any request arrives. The fix is to write /users/{id}.

Declaring the Wrong Integer Type

// Wrong for ids above 255 - use i32 or i64 for ids
async fn get_user(Path(id): Path<u8>) -> String {
    format!("User {}", id)
}

A u8 holds values from 0 to 255, so /users/1000 is rejected even though 1000 is a perfectly good id. The rejection is correct behavior for the declared type, but the type is wrong for the job. Use i32 for ordinary ids and i64 when ids can grow large. The same trap applies to u32 with negative ids: /users/-5 is rejected because a u32 cannot be negative.

Expecting a Rejection for a Missing Segment

// Wrong expectation - /users/ with no id is a 404, not a 400
assert_eq!(status, StatusCode::BAD_REQUEST);

A missing segment means no route matched, and routing answers 404 with an empty body before any extractor runs. A rejection needs a segment that is present but unparsable. Test the two cases separately, as the test file above does.

Matching on the Full Body Text in Client Code

The detail after the colon changes with every bad value, so a client that compares the whole body against one fixed string breaks on the next bad id. Match the status code, and if the body is needed, check that it starts with Invalid URL or contains the segment that failed.

Final Complete Example

Here is the whole project in one place: single and multi segment routes, the server entry point, the dependencies, and the test file.

// src/lib.rs
use axum::{extract::Path, routing::get, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct PostPath {
    user_id: i32,
    post_id: i32,
}

pub fn app() -> Router {
    Router::new()
        .route("/users/{id}", get(get_user))
        .route("/users/{user_id}/posts/{post_id}", get(get_post))
}

async fn get_user(Path(id): Path<i32>) -> String {
    format!("User {}", id)
}

async fn get_post(Path(params): Path<PostPath>) -> String {
    format!("Post {} by user {}", params.post_id, params.user_id)
}
// src/main.rs
use axum_project::app;

#[tokio::main]
async fn main() {
    let app = app();
    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();
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
// tests/path_rejection_test.rs
use axum::{
    body::{to_bytes, Body},
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

async fn get(uri: &str) -> (StatusCode, String) {
    let response = app()
        .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
        .await
        .unwrap();
    let status = response.status();
    let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    (status, String::from_utf8_lossy(&bytes).to_string())
}

#[tokio::test]
async fn bad_id_is_rejected_with_400() {
    let (status, body) = get("/users/abc").await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body, "Invalid URL: Cannot parse `abc` to a `i32`");
}

#[tokio::test]
async fn good_multi_segment_route_works() {
    let (status, body) = get("/users/7/posts/3").await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "Post 3 by user 7");
}

Run the server with cargo run and the tests with cargo test. A numeric id returns a user, a non numeric id returns a 400 with the value named, and a missing segment returns a 404 from routing.

Summary

A Path rejection is the narrowest rejection in this cluster. One piece of text, one declared type, one parse attempt, and one clear failure message. The lesson that carries forward is the split between two kinds of bad URL: a URL that matches no route gets a 404 from routing, while a URL that matches a route but carries a segment of the wrong shape gets a 400 from the extractor. That split is the reason the handler can trust its i32 completely. The same split shows up again with the other extractors, where the input is a whole body or a whole query string instead of one segment, and where the number of ways to fail grows. The practical rule to keep is simple: declare the type the value really has, let the extractor reject the rest, and read the status code before reading the body.