Type-driven extractors

Learn what type-driven extractors are in Axum, why they make request handling simple and safe, and how to use them in your Rust handlers

Type-driven extractors

When you write a handler function in Axum, the function's parameters are not just regular values you pass in manually. Each parameter tells Axum what piece of the incoming HTTP request you want, and Axum figures out how to get it for you. That idea is called type-driven extraction.

Think of it like ordering at a restaurant. You don't walk into the kitchen and grab the ingredients yourself. You tell the waiter what you want by naming the dish, and the waiter brings it to your table. In Axum, your handler function's parameter types are the order, and the framework is the waiter. You say "I want the path parameter as a u64" by writing Path<u64>, and Axum goes into the request, finds the path segment, parses it into a u64, and hands it to you.

This page explains what type-driven extractors are, why they exist, how they work under the hood, and how to use them in your own handlers. We'll start with the simplest possible example and build up to writing your own custom extractor.

A first look at an extractor

The most common extractor you'll meet is Path. It pulls a value out of the URL path. Here is a complete handler that uses it:

use axum::extract::Path;
async fn get_user(Path(user_id): Path<u64>) -> String {
    format!("You asked for user {user_id}")
}

This function takes one argument: Path<u64>. The Path part is the extractor, and the u64 inside the angle brackets is the type you want the path segment to become. The pattern Path(user_id) unwraps the extracted value into the variable user_id.

When Axum calls this handler, it looks at the route that matched. If the route was defined as /users/{id}, then Axum knows that the first path segment after users/ should be turned into a u64. It reads the string "42" from the URL, tries to parse it as a u64, and if that succeeds, it calls your handler with user_id set to 42.

If the URL says /users/abc, the parsing fails because "abc" is not a number. In that case Axum does not call your handler at all. Instead, it returns an error response to the client automatically. That is a key part of type-driven extraction: if the data cannot become the type you asked for, the request is rejected before your code runs.

Why type-driven extraction exists

Before frameworks like Axum, many web frameworks forced you to manually read request data from a big request object. You would write something like:

let id = request.params.get("id").unwrap();
let id_number = id.parse::<u64>().unwrap();

Every handler repeated this boilerplate. It was easy to forget a step, use the wrong type, or mishandle an error. Axum's type-driven approach removes that repetition. You declare what you want in the function signature, and Axum does the boring work of finding, parsing, and validating it.

Type-driven extraction also gives you compile-time safety. If you write a parameter type that Axum does not know how to extract, your program will not compile. The compiler will tell you exactly what is wrong. You cannot accidentally put a body extractor in the wrong position or use an unsupported type without the Rust compiler catching it. This is much safer than frameworks that only fail at runtime when a request arrives.

Another benefit is readability. A handler signature like this:

use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateParams {
    page: Option<u32>,
}
#[derive(Deserialize)]
struct UpdateUser {
    name: String,
}
async fn update_user(
    Path(user_id): Path<u64>,
    Query(params): Query<UpdateParams>,
    Json(payload): Json<UpdateUser>,
) -> String

tells you almost everything about the route: it expects a numeric user ID in the path, some query parameters that match UpdateParams, and a JSON body that matches UpdateUser. The signature is self-documenting. A new developer can look at this function and immediately understand what the endpoint expects.

The trait behind every extractor

In Axum, an extractor is any type that implements one of two traits:

  • FromRequestParts - for extractors that only need the request's head (method, URI, headers, etc.) and not the body.
  • FromRequest - for extractors that need to consume the request body.

FromRequestParts gets a &mut Parts object, which is basically the request without the body. Extractors like Path, Query, and HeaderMap implement this trait because they only read from the URL or headers.

FromRequest gets the entire request, including the body, and it is allowed to take the body out. Extractors like Json, Form, String, and Bytes implement FromRequest because they need to read and parse the body data.

When you write a handler like:

async fn handler(Path(id): Path<u64>, Json(payload): Json<SomeType>)

Axum looks at each argument and checks whether its type implements the appropriate trait. The Path<u64> type implements FromRequestParts, so Axum calls that trait's method with the request parts. The Json<SomeType> type implements FromRequest, so Axum calls that trait's method with the whole request, and that method will consume the body.

The trait also defines an associated type called Rejection. That is the error type returned when extraction fails. For example, Path<u64> rejects with a type that indicates the path parameter was missing or could not be parsed as a number. Axum converts that rejection into an HTTP error response automatically, usually with a status code like 400 Bad Request or 422 Unprocessable Entity.

Common built-in extractors

Axum ships with many extractors that cover the most common needs. Let's look at a few of them, starting with the simplest.

Path extractor

Path extracts parameters from the URL path. You define the route with a placeholder in curly braces, like /users/{id}. Then the handler can use Path<T> where T is any type that implements serde::Deserialize, such as u64, String, or even a custom type. (Path segments are deserialized with serde - not parsed with FromStr - which is why a struct with named fields can also be used.)

use axum::{
    extract::Path,
    routing::get,
    Router,
};
async fn get_user(Path(user_id): Path<u64>) -> String {
    format!("User ID: {user_id}")
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

You can also extract multiple path parameters by using a tuple inside Path:

use axum::{
    extract::Path,
    routing::get,
    Router,
};
async fn get_comment(
    Path((post_id, comment_id)): Path<(u64, u64)>,
) -> String {
    format!("Post {post_id}, Comment {comment_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("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Path parameter syntax:

Axum 0.8 uses curly braces {param} for route placeholders. Older versions used a colon :param. If you see a colon in older tutorials, replace it with curly braces.

Query extractor

Query pulls parameters from the query string, the part of the URL after the ?. It deserializes them into a struct that implements serde::Deserialize.

use axum::{
    extract::Query,
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    per_page: Option<u32>,
}
async fn list_items(Query(pagination): Query<Pagination>) -> String {
    let page = pagination.page.unwrap_or(1);
    let per_page = pagination.per_page.unwrap_or(20);
    format!("Page {page}, showing {per_page} items")
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/items", get(list_items));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /items?page=2&per_page=50 will produce "Page 2, showing 50 items". The query string page=2&per_page=50 is parsed into the Pagination struct using serde's deserialization rules.

Query parameter names must match struct fields:

The field names in your struct must match the query parameter names exactly. If your struct has per_page but the URL sends perPage, deserialization will fail and the request will be rejected with a 400 error.

Repeated query keys need axum-extra:

Axum's built-in Query uses serde_urlencoded, which does not collect repeated keys into a Vec - for ?tag=rust&tag=axum it keeps only the last value. If you need multi-value parameters, use the Query extractor from axum-extra (axum_extra::extract::Query), which is backed by serde_html_form and does collect repeated keys into a Vec (or any sequential container).

Json extractor

Json consumes the request body and deserializes it as JSON into a type that implements Deserialize. It is one of the most used extractors for building REST APIs.

use axum::{
    extract::Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
}
async fn create_user(Json(payload): Json<CreateUser>) -> String {
    format!("Created user {} with email {}", payload.username, payload.email)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When a client sends a POST request to /users with a JSON body like {"username":"alice","email":"alice@example.com"}, Axum reads the body, calls serde_json to turn it into a CreateUser struct, and passes that to your handler.

Json requires the Content-Type header:

The Json extractor will reject the request with a 415 Unsupported Media Type error if the request does not include a Content-Type: application/json header. This is a frequent source of confusion when testing with curl without specifying the header.

Other common extractors

Axum provides many more extractors out of the box:

  • Form<T> - like Json but for application/x-www-form-urlencoded form data.
  • String - consumes the body and returns it as a UTF-8 string.
  • Bytes - consumes the body and returns it as raw bytes.
  • HeaderMap - gives you all request headers.
  • Method - gives you the HTTP method (GET, POST, etc.).
  • Request - gives you the entire request object.
  • State<T> - provides access to application state (covered in its own page).

You do not need to memorize all of them now. The important idea is that each one is a type that implements one of the extractor traits, and you use it by putting it as a handler parameter.

Combining extractors and the ordering rule

A handler can take multiple extractors at once. Axum runs them from left to right, and the extracted values are passed to the function in that order. This is useful because one endpoint often needs data from several parts of the request.

Here is an example that combines Path, Query, and Json:

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(user_id): Path<u64>,
    Query(pagination): Query<Pagination>,
    Json(payload): Json<UpdateUser>,
) -> String {
    format!(
        "Updating user {user_id} on page {} with new name {}",
        pagination.page.unwrap_or(1),
        payload.name
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", post(update_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The order matters because extractors are processed sequentially. But there is an important restriction: only one extractor can consume the request body, and it must be the last argument. The body is a stream that can only be read once. If you tried to have two body extractors, like String and Json, Axum would have to read the body twice, which is impossible.

Axum enforces this rule at compile time. If you write a handler where a body-consuming extractor is not last, or if you have two of them, the code will not compile. The compiler error will explain that the last extractor must implement FromRequest and all previous ones must implement FromRequestParts.

use axum::{
    extract::{Path, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Payload {
    name: String,
}
// This will NOT compile because Json consumes the body and is not last
/*
async fn bad_handler(
    Json(payload): Json<Payload>,
    Path(id): Path<u64>,
) {}
*/

The fix is always to reorder the parameters so the body-consuming extractor comes last:

async fn good_handler(
    Path(id): Path<u64>,
    Json(payload): Json<Payload>,
) -> String {
    format!("User {id}, name {}", payload.name)
}

Body extractors must be last:

If you forget this rule, the compiler will catch it for you. The error may look intimidating, but the key part usually says something like "the trait bound Json<Payload>: FromRequestParts is not satisfied". That is Axum's way of saying "you put a body extractor in a position where I can only use a parts extractor".

Handling extractor rejections inside a handler

By default, if an extractor fails, Axum returns an error response and your handler never runs. But sometimes you want to handle that failure yourself. For example, you might want to return a custom error message or a different status code than the default.

You can do this by wrapping the extractor in a Result. The error type is the extractor's specific rejection type. Axum knows that if you write Result<T, Rejection> where T is an extractor, then the extraction will still happen, but instead of aborting on failure, the Err value will be passed to your handler.

Here is an example with Json:

use axum::{
    extract::{Json, rejection::JsonRejection},
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    username: String,
}
async fn create_user(payload: Result<Json<CreateUser>, JsonRejection>) -> String {
    match payload {
        Ok(Json(user)) => format!("Created user {}", user.username),
        Err(rejection) => {
            // You can inspect the kind of rejection and respond differently
            match rejection {
                JsonRejection::MissingJsonContentType(_) => {
                    "Missing Content-Type: application/json".to_string()
                }
                JsonRejection::JsonSyntaxError(err) => {
                    format!("Invalid JSON syntax: {err}")
                }
                _ => "Bad request".to_string(),
            }
        }
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Notice that the handler still receives a Result. Inside the handler, you decide what to do. You could return a custom response with a specific status code and body. The JsonRejection type has several variants that describe exactly what went wrong, so you can give precise feedback to the client.

This approach is useful when you need different error handling for the same extractor in different parts of your application. But if you find yourself writing the same match over and over, you might want to create a custom extractor that handles the rejection internally (we'll see that later).

The JsonRejection variants map to different statuses, which is why matching on them is useful: MissingJsonContentType means the request had no (or the wrong) Content-Type and is a 415 Unsupported Media Type; JsonSyntaxError means the body is not valid JSON and is a 400 Bad Request; JsonDataError means the JSON parsed but did not fit the target type (for example a missing field) and is a 422 Unprocessable Entity. The remaining variant, BytesRejection, covers failures reading the body itself - including a body over the size limit, which is a 413 Payload Too Large (see "The default 2 MB body limit" below).

The default 2 MB body limit

Extractors built on Bytes - Bytes itself, String, Json, and Form - refuse bodies larger than 2 MB by default. Change the limit with the DefaultBodyLimit layer, on the whole router or on a single route:

use axum::{extract::DefaultBodyLimit, routing::post, Router};

// A small handler that echoes how many bytes it received.
async fn upload(body: axum::body::Bytes) -> String {
    format!("Received {} bytes", body.len())
}

#[tokio::main]
async fn main() {
    // Allow JSON bodies up to 10 MB on every route.
    let app = Router::new()
        .route("/upload", post(upload))
        .layer(DefaultBodyLimit::max(10 * 1024 * 1024));

    // Or remove the limit entirely for one route (pair it with a
    // tower_http::limit::RequestBodyLimitLayer if the client is untrusted).
    let _app_unlimited = Router::new()
        .route("/upload", post(upload).layer(DefaultBodyLimit::disable()));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Optional extractors with Option

Some extractors can be used inside Option. This means that if the data is not present, instead of rejecting the request, the extractor will simply give you None. This is especially handy for optional path parameters or optional headers.

Not all extractors support Option. Only those that implement the special traits OptionalFromRequestParts or OptionalFromRequest can be used this way. In axum 0.8 the built-in extractors that support it are Path and MatchedPath - not Query, and not Extension. (Host supports it too, but it lives in axum-extra, not in axum itself.) Wrapping Query in Option does not compile in axum 0.8, because Query implements only FromRequestParts and has no OptionalFromRequestParts implementation. For optional query parameters, the usual pattern is to make the fields of the struct optional instead - Query<Pagination> where Pagination has page: Option<u32> already gives you None for a missing page. Axum-extra also offers an OptionalQuery extractor that returns None when there is no query string at all.

Here is a working example with Path. Option<Path<T>> gives you None when the route captured no path parameters, so one handler can serve both /users (a list) and /users/{id} (a single user):

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

async fn get_user(maybe_id: Option<Path<u64>>) -> String {
    match maybe_id {
        Some(Path(id)) => format!("Fetching user {id}"),
        None => "Listing all users".to_string(),
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", get(get_user))
        .route("/users/{id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /users gives you "Listing all users" because no path parameter was captured. A request to /users/42 gives you "Fetching user 42".

The exact behaviour of Option<Extractor> is defined by the extractor itself. For Path, a present-but-unparsable value still rejects the request (a 400) rather than giving None - None only means "nothing was captured". Custom extractors can define their own OptionalFromRequestParts implementation to decide which cases mean "absent" and which are still errors. Always read the specific extractor's docs to understand what None means for that type.

Option extraction semantics vary:

The exact behavior of Option<Extractor> is defined by the extractor itself. For Path, no captured parameter gives None, but a captured value that fails to parse into the target type will still reject the request. Always read the specific extractor's docs to understand what None means for that type.

Writing your own custom extractor

The real power of type-driven extraction shows when you create your own extractors. A custom extractor is just a type that implements FromRequestParts or FromRequest. This lets you encapsulate request validation and parsing logic in one place and reuse it across many handlers.

For example, suppose many of your handlers need to read a User-Agent header and reject the request if it is missing. You could write an extractor that does this:

use axum::{
    extract::FromRequestParts,
    http::{
        header::{HeaderValue, USER_AGENT},
        request::Parts,
        StatusCode,
    },
};
struct ExtractUserAgent(HeaderValue);
impl<S> FromRequestParts<S> for ExtractUserAgent
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        if let Some(user_agent) = parts.headers.get(USER_AGENT) {
            Ok(ExtractUserAgent(user_agent.clone()))
        } else {
            Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing"))
        }
    }
}

Let's unpack this. The struct ExtractUserAgent is just a wrapper around a HeaderValue. We implement FromRequestParts for it, which means it can be used as a handler parameter that does not consume the body. The generic S is the state type, which we don't need here, so we keep it unconstrained but require Send + Sync as is typical.

The associated type Rejection is the error we return if something goes wrong. Here we use a tuple of (StatusCode, &'static str), which Axum knows how to turn into an HTTP response.

The method from_request_parts receives a mutable reference to Parts, which gives access to the request head. We look for the User-Agent header. If it's there, we clone it and wrap it. If not, we return an error with status 400 and a message.

Now we can use this extractor in a handler just like any built-in one:

use axum::{routing::get, Router};
async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) -> String {
    format!("Your user agent is: {}", user_agent.to_str().unwrap_or("unknown"))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

If a request comes without the User-Agent header, Axum will return the 400 response we defined, and handler will not be called. This is great for reusing validation logic across endpoints.

Implementing FromRequest for body-consuming extractors

If your extractor needs to read the request body, you must implement FromRequest instead. This trait gives you the whole request, and you are allowed to consume the body.

Here's an example that reads the body as raw bytes and ensures it is not too large:

use axum::{
    extract::FromRequest,
    body::Bytes,
    http::{Request, StatusCode},
};
struct LimitedBody(Bytes);
impl<S> FromRequest<S> for LimitedBody
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request(req: Request<axum::body::Body>, _state: &S) -> Result<Self, Self::Rejection> {
        // axum::body::to_bytes consumes the body and returns Bytes
        let bytes = axum::body::to_bytes(req.into_body(), 1024 * 1024)
            .await
            .map_err(|_| (StatusCode::BAD_REQUEST, "Failed to read body"))?;
        if bytes.len() > 10 * 1024 {
            return Err((StatusCode::PAYLOAD_TOO_LARGE, "Body too large"));
        }
        Ok(LimitedBody(bytes))
    }
}

The from_request method receives the full Request object. We use axum::body::to_bytes to collect the body with a maximum size limit (1 MB in this call). If the body is too large, we return a 413 Payload Too Large error. Otherwise, we return the bytes wrapped in our LimitedBody type.

Using this extractor in a handler is the same as before:

use axum::{routing::post, Router};
async fn upload(LimitedBody(data): LimitedBody) -> String {
    // The pattern `LimitedBody(data)` unwraps the tuple struct, so `data`
    // is already the `Bytes` - call `.len()` on it directly.
    format!("Received {} bytes", data.len())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/upload", post(upload));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Because this extractor consumes the body, it must be the last argument in the handler if you use other extractors.

Custom extractors centralize validation:

When you implement a custom extractor, all the parsing and validation logic lives in one place. Every handler that uses it automatically gets that logic. If you later need to change how the header is validated or the body size limit, you change only the extractor, not every handler. This makes your code easier to maintain.

The two extractor traits side by side

Choosing between FromRequestParts and FromRequest is the main decision when writing a custom extractor. The rule is simple: if you don't need the body, use FromRequestParts. If you do, use FromRequest.

FromRequestParts - metadata only

Use this when your extractor only reads metadata: method, URI, headers, extensions, etc.

use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
};
struct MyExtractor(String);
impl<S> FromRequestParts<S> for MyExtractor
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        // You have access to parts.method, parts.uri, parts.headers, etc.
        if let Some(value) = parts.headers.get("x-custom") {
            Ok(MyExtractor(value.to_str().unwrap().to_string()))
        } else {
            Err((StatusCode::BAD_REQUEST, "Missing x-custom header"))
        }
    }
}

The key point: you get a &mut Parts, which is everything except the body. You cannot read the body here.

FromRequest - needs the body

Use this when you need the body of the request.

use axum::{
    extract::FromRequest,
    http::{Request, StatusCode},
};
struct MyBodyExtractor(String);
impl<S> FromRequest<S> for MyBodyExtractor
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request(req: Request<axum::body::Body>, _state: &S) -> Result<Self, Self::Rejection> {
        // You can consume the body, e.g., using axum::body::to_bytes
        let bytes = axum::body::to_bytes(req.into_body(), 1024 * 1024)
            .await
            .map_err(|_| (StatusCode::BAD_REQUEST, "Failed to read body"))?;
        let text = String::from_utf8(bytes.to_vec())
            .map_err(|_| (StatusCode::BAD_REQUEST, "Body is not UTF-8"))?;
        Ok(MyBodyExtractor(text))
    }
}

Here you receive a Request<Body>, which includes the body stream. You are allowed to take the body and consume it. This extractor must be the last parameter in your handler.

The choice is not a matter of preference but of need. If you only need headers, do not consume the body; other extractors later might need it. If you consume the body, no other extractor after you can read it.

Common mistakes and how to avoid them

Type-driven extractors are easy to use once you understand the rules, but beginners often trip on a few points.

Forgetting that body extractors must be last

As already mentioned, the most common compile error is putting a body-consuming extractor before a parts extractor. The compiler error may be long and confusing. Look for a message like the trait bound ... is not satisfied. The solution is always to reorder the parameters so the body extractor is last.

Not adding the required serde derives

When using Json or Query with a custom struct, that struct must implement Deserialize from serde. If you forget the #[derive(Deserialize)] attribute, the compiler will complain that the struct doesn't implement Deserialize.

// Wrong - missing Deserialize
struct CreateUser {
    username: String,
}
// Correct
#[derive(serde::Deserialize)]
struct CreateUser {
    username: String,
}

Assuming Option always means "no data"

Option<Extractor> does not mean "ignore any errors and give me None". It means the extractor can decide what absence means. For example, Option<Json<T>> is not available for Json because the body cannot be absent in a meaningful way; a missing body would be an error, not None. Always check the documentation for the specific extractor to see if it supports Option and what None represents.

Trying to consume the body twice

If you have two extractors that both try to read the body, the second one will get an empty body or an error because the first one already consumed it. Axum prevents this at compile time by enforcing the last-extractor rule, but if you write a custom extractor that consumes the body and then also try to use String after it, the compiler will stop you. The only safe way is to have exactly one body-consuming extractor, and it must be last.

Not handling rejection types correctly when using Result

When you wrap an extractor in Result, the error type must be exactly the extractor's Rejection type. For Json<T>, that is JsonRejection. For Path<T>, it is PathRejection. If you use Result<Json<T>, SomeOtherError>, the compiler will complain. Use the rejection type associated with the extractor.

Do not ignore extractor rejections:

If an extractor fails and you are not using Result, Axum returns a default error response, often with a generic 400 or 422 status. That may be okay for quick prototypes, but for a real API, you usually want to customize the error response. Using Result or a custom extractor gives you that control. Ignoring rejections can lead to clients receiving cryptic errors.

Practical real-world usage

Type-driven extractors are at the heart of every Axum application. They appear in almost every handler you will write. When you build a REST API, you will use Path for resource IDs, Query for filtering and pagination, Json for request bodies, and State for shared application data. By declaring these in the function signature, you get a clear, type-safe contract for each endpoint.

In production codebases, teams often define shared structs for query parameters and request bodies, and then reuse them across many handlers. They might also create custom extractors for common tasks like checking authentication headers, validating API keys, or applying size limits to uploads. This keeps handlers small and focused on business logic, while the extractor handles the request plumbing.

Consider this handler from a typical user management service:

use axum::{
    extract::{Path, Query, State, Json},
    http::StatusCode,
    response::IntoResponse,
    routing::post,
    Router,
};
use serde::Deserialize;
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    app_name: String,
}
#[derive(Deserialize)]
struct UserFilter {
    active: Option<bool>,
}
#[derive(Deserialize)]
struct UpdateUser {
    email: String,
}
async fn update_user(
    State(app_state): State<Arc<AppState>>,
    Path(user_id): Path<u64>,
    Query(filter): Query<UserFilter>,
    Json(payload): Json<UpdateUser>,
) -> impl IntoResponse {
    println!(
        "{}: updating user {} (active filter: {:?}) with email {}",
        app_state.app_name, user_id, filter.active, payload.email
    );
    StatusCode::OK
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState { app_name: "demo".to_string() });
    let app = Router::new()
        .route("/users/{id}", post(update_user))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This signature communicates a lot: the endpoint needs shared state, a numeric user ID, optional query filters, and a JSON body with an email. There is no boilerplate to fetch any of these; Axum did it all before the function body started.

How beginners should think about type-driven extractors

If you are new to Axum, the easiest mental model is: a handler function is a list of requirements you place on an incoming request. Each parameter type is a requirement. If the request cannot satisfy all the requirements, the request is rejected and the handler never runs. If it can satisfy them, the extracted values are handed to you in a convenient form.

You do not need to understand the trait implementations in detail to use built-in extractors. Just know that when you write Path<u64>, Axum will attempt to parse that path segment as a u64. When you write Json<MyStruct>, Axum will read the body and deserialize it into MyStruct. That is all you need to start building endpoints.

As you become comfortable, you can start writing your own extractors to encapsulate repeated validation. But even then, the core idea remains the same: the type tells Axum what to extract, and Axum does the rest.

Summary

Type-driven extractors are a defining feature of Axum's design. They replace manual request parsing with a declarative, compile-time checked system. By simply declaring the types you need as handler parameters, you get automatic extraction, validation, and error handling. The order of parameters is meaningful, with body-consuming extractors required to be last. You can customize behavior by using Result for manual rejection handling, Option for optional data, or by implementing your own extractor with FromRequestParts or FromRequest.

The single most important insight is that your handler signature becomes a contract for the endpoint. It documents exactly what the client must send, and the Rust compiler enforces that contract before your code even runs. This leads to fewer runtime surprises, clearer code, and a more maintainable codebase.