Extractor arguments in handlers

Learn how Axum handlers accept data from requests through extractor arguments including paths, queries, headers, bodies, and application state with beginner-friendly examples

Handlers in Axum do not reach into a global request object. Instead, each piece of data a handler needs shows up as an argument. Axum figures out how to provide that argument by looking at its type. A Path<u32> gets the numeric segment from the URL, a Json<CreateUser> parses the request body as JSON, and a HeaderMap gives you the raw HTTP headers. This mechanism is called extraction, and the argument types are called extractors.

Before this page, you saw handlers as async fn functions that return responses. Here, the focus is entirely on what goes into the handler - the arguments.

The mental model for extractors

Imagine the handler as a clerk at a desk. A customer arrives with a form containing many fields. The clerk does not grab the entire form and dig through it; instead, someone before the clerk reads the form, validates each needed field, and places exactly those fields on the desk. The clerk only picks up what the job requires.

In Axum, the framework sits before your handler and plays that preparing role. For every argument your handler declares, Axum looks up a matching extractor, runs it against the incoming request, and if extraction succeeds, calls your handler with the extracted value. If any extractor fails - say the URL segment is missing or the JSON is malformed - Axum returns an error response and your handler never runs.

This separation keeps handlers clean. The handler focuses on business logic, not on reading headers, parsing bodies, or checking for missing data.

Why this page matters:

Every Axum handler you write beyond the most trivial example will use at least one extractor. Understanding extractors is the key to writing handlers that feel natural in Axum.

A minimal starter example

The simplest useful extractor is Path. It pulls a dynamic segment from the URL.

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

Here, get_user declares a single argument: Path(user_id). The Path<u32> tells Axum to look at the URL, find the {user_id} segment, convert it to a u32, and bind it to the user_id variable. The Path(...) wrapper is a Rust pattern - it unpacks the value inside the Path type. If the URL is /users/42, the handler receives user_id = 42 and returns "You asked for user 42". If the URL is /users/hello, the conversion to u32 fails, Axum returns a 400 Bad Request, and the handler never runs.

This single example shows the three-step extractor workflow. Axum first determines what the type means, then runs the extraction logic, then either calls the handler with the value or rejects the request.

Why extractor arguments exist

Before frameworks like Axum, web handlers often received a single Request object and did everything manually. You would call request.params("id"), parse it, handle the parse error, and repeat for every route. That code was repetitive and error-prone.

Axum inverts the model. The type signature of your handler declares exactly what data you need. Axum reads that signature, performs the extraction and validation, and hands you ready-to-use values. This has several practical effects.

First, handlers become shorter. If a route needs only a query parameter, the handler declares Query<Params> and nothing else. Second, validation is centralized. Every route that uses Path<u32> gets integer parsing and error handling for free, without a single match in your own code. Third, the handler's type signature serves as documentation. Another developer can see (Path<Uuid>, Extension<AuthUser>, Json<CreatePost>) and immediately understand what the route expects.

The signature can grow

The Path example only had one extractor. Handlers can declare multiple extractor arguments, and Axum will run them all before calling the handler. The order matters, but more on that in a moment.

Two more crates appear from here on that the starter project does not have yet: serde, for turning query strings and JSON into Rust structs, and uuid, for user IDs shaped like 550e8400-e29b-41d4-a716-446655440000. Add them to Cargo.toml:

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

Here is a handler that accepts both a path parameter and query parameters.

use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
use uuid::Uuid;
#[derive(Deserialize)]
struct Pagination {
    page: usize,
    per_page: usize,
}
async fn list_user_posts(
    Path(user_id): Path<Uuid>,
    Query(pagination): Query<Pagination>,
) -> String {
    format!(
        "Fetching posts for user {}, page {}, {} per page",
        user_id, pagination.page, pagination.per_page
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}/posts", get(list_user_posts));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The handler has two extractors. Path<Uuid> extracts the user ID from the path and attempts to parse it as a UUID. Query<Pagination> extracts the query string - everything after ? in the URL - and deserializes it into the Pagination struct. For Pagination to work, the struct must derive Deserialize from Serde, because Query uses Serde to parse key-value pairs.

A request to /users/550e8400-e29b-41d4-a716-446655440000/posts?page=2&per_page=15 gives the handler user_id = 550e8400-e29b-41d4-a716-446655440000, pagination.page = 2, and pagination.per_page = 15. If the UUID is malformed, extraction fails before the query string is even touched.

Missing fields cause rejection:

For Query<Pagination>, if page or per_page is missing from the query string, Axum returns a 400 Bad Request and the handler is never called. Unlike path segments, query parameters are optional in the URL, but Query<T> treats them as required unless the struct fields use Option or default values.

The request body can be an extractor

Extractors are not limited to URL data. The request body - the data sent in a POST, PUT, or PATCH request - can also be extracted. The simplest body extractor is String, which collects the raw body into a UTF-8 string.

use axum::{
    routing::post,
    Router,
};
async fn echo_string(body: String) -> String {
    body
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo_string));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

If a client sends POST /echo with the body Hello from the client, the handler receives body = "Hello from the client" and returns it. This is a valid extractor because String implements FromRequest, meaning it can consume the request body.

A more practical body extractor is Json<T>. It reads the body, parses it as JSON, and deserializes it into a Rust type.

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

When a client sends POST /users with the JSON body {"email": "alice@example.com", "password": "secret"}, the Json<CreateUser> extractor reads the body, deserializes it into CreateUser, and gives the handler payload.email = "alice@example.com". If the body is not valid JSON, or if the JSON lacks the email or password field, Axum returns 400 Bad Request and the handler does not run.

The Json(...) pattern in the argument unpacks the payload. Json<CreateUser> is the extractor type; the Json(payload) pattern gives you the CreateUser value inside it.

Common extractors at a glance

Axum ships with many built-in extractors. The table lists the ones beginners encounter first. Each maps to a different part of an incoming request.

ExtractorWhat it extractsExample URL or request
Path<T>Dynamic path segments/users/{id} → Path<u32>
Query<T>Query string parameters/search?q=axum → Query<SearchParams>
HeaderMapAll HTTP headersAuthorization: Bearer ...
StringRaw request body as UTF-8POST /echo body hello
BytesRaw request body as bytesPOST /upload binary data
Json<T>JSON request bodyPOST /users body {...}
Extension<T>Values inserted into the request by middlewareCustom type added via Extension
RequestThe whole HTTP requestIncludes method, URI, headers, body

The Request extractor is special because it gives you the entire request object. It consumes the request, meaning you cannot use it with another body-consuming extractor. But for cases where you need to inspect the method, URI, and headers all at once, it is the right tool.

use axum::{
    extract::Request,
    routing::get,
    Router,
};
async fn inspect_request(request: Request) -> String {
    format!(
        "Method: {}, URI: {}, Headers count: {}",
        request.method(),
        request.uri(),
        request.headers().len()
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/inspect", get(inspect_request));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A GET /inspect request produces output like Method: GET, URI: /inspect, Headers count: 3 - the count is whatever the client actually sent, and a real HTTP client always sends at least Host (plus usually User-Agent and Accept), so don't expect it to be 1. The Request extractor is uncommon for typical CRUD handlers because more specific extractors are clearer, but it exists for cases where you need fine-grained control.

How Axum knows what each argument means

You do not register extractors anywhere. Axum determines what an argument means by its type. This works through two Rust traits defined in the axum::extract module.

The first trait is FromRequestParts. It runs without consuming the request body. Extractors like Path, Query, HeaderMap, and Extension implement this trait because they only need the request's head - the method, URI, version, and headers.

The second trait is FromRequest. It can consume the request body. Extractors like String, Bytes, and Json implement this trait because they need the bytes that come after the headers.

Every extractor type has a Rejection associated type. When extraction fails, the extractor returns a Rejection, which Axum converts into an HTTP error response. Path<u32> fails with a PathRejection when the segment is not a valid integer. Json<T> fails with a JsonRejection when the body is not valid JSON.

The extractor also receives the application state. Even if you are not using state yet, every FromRequestParts and FromRequest implementation is generic over a state type S. This is why the methods work across different application setups. State is a value you attach to the router with .with_state(...), and extractors can read a shared copy of it.

The order of extractor arguments matters

Because Axum processes extractors from left to right, the order you write them in the function signature is significant. If the first extractor fails, the later ones never run.

A more specific rule involves the request body. The body is a stream - it can be read once. Therefore, only one extractor can consume the body per handler. Axum enforces this with a compile-time rule: the last argument can implement FromRequest (body-consuming), and all other arguments must implement FromRequestParts (non-body-consuming).

This handler is valid. The Method, HeaderMap, and State extractors are all FromRequestParts, and the body-consuming String extractor is last.

use axum::{
    extract::State,
    http::{HeaderMap, Method},
    routing::post,
    Router,
};
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn handler(
    method: Method,
    headers: HeaderMap,
    State(state): State<AppState>,
    body: String,
) -> String {
    format!(
        "Method: {}, App: {}, Body: {}",
        method,
        state.app_name,
        body
    )
}
#[tokio::main]
async fn main() {
    let state = AppState {
        app_name: "My App".to_string(),
    };
    let app = Router::new()
        .route("/process", post(handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Putting body: String before method: Method will not compile. Rust will not give you a clean error message. You will see something like the trait bound Handler<_, _> is not implemented without a clear explanation. The issue is that you tried to use a body-consuming extractor before other extractors.

The one body extractor rule:

Even if you put String and Json<T> adjacent, the request body can only be read once. Having two body-consuming extractors in one handler is a compile error. Axum tells you this by requiring the final argument to implement FromRequest and all earlier ones to implement FromRequestParts. Two body extractors cannot both be last, so the second one always breaks the rule and the handler does not compile.

Here is an invalid handler that attempts to read the body twice. It will not compile.

use axum::extract::Json;
use serde::Deserialize;
#[derive(Deserialize)]
struct Payload {
    name: String,
}
async fn broken_handler(
    string_body: String,
    json_body: Json<Payload>,
) {
    // This handler will never run because it does not compile.
    // The body can only be consumed once.
}

A beginner might think String and Json<Payload> could both read the body because they are different types. But both try to consume the same underlying bytes, and that is impossible. Axum catches this at compile time, which is better than a runtime panic but can be confusing until you know the rule.

Handling extractor failures with Result

By default, a failed extractor produces an automatic error response. For Path<u32>, that response is 400 Bad Request with a plain-text body. You do not need to write any error handling. But sometimes you want to customize the response or log the failure.

For that, you can wrap an extractor in Result<T, T::Rejection>. The extractor will no longer reject the request globally. Instead, if extraction fails, the handler is called with Err(rejection), and you decide what to do.

use axum::{
    extract::{Json, rejection::JsonRejection},
    response::IntoResponse,
    routing::post,
    http::StatusCode,
    Router,
};
use serde_json::Value;
async fn create_user(payload: Result<Json<Value>, JsonRejection>) -> impl IntoResponse {
    match payload {
        Ok(json) => {
            let value = json.0;
            (StatusCode::CREATED, format!("Received: {}", value))
        }
        Err(JsonRejection::MissingJsonContentType(_)) => {
            (StatusCode::BAD_REQUEST, "Content-Type must be application/json".to_string())
        }
        Err(JsonRejection::JsonDataError(_)) => {
            (StatusCode::BAD_REQUEST, "JSON data is invalid".to_string())
        }
        Err(JsonRejection::JsonSyntaxError(_)) => {
            (StatusCode::BAD_REQUEST, "JSON syntax error".to_string())
        }
        Err(JsonRejection::BytesRejection(_)) => {
            (StatusCode::INTERNAL_SERVER_ERROR, "Failed to buffer request body".to_string())
        }
        Err(_) => {
            (StatusCode::BAD_REQUEST, "Unknown JSON error".to_string())
        }
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The Result wrapper tells Axum to call the handler no matter what. On success, the handler receives Ok(json). On failure, it receives Err(JsonRejection::...) with a specific variant indicating what went wrong. You can match on those variants to produce different responses, log the failure, or fall back to a default value.

Result gives you control:

Using Result<T, Rejection> as an extractor argument is the recommended way to handle extractor errors locally within a handler. For a shared error format across many handlers, define one error type and reuse it as the Err variant everywhere. But for per-handler control, Result is the right tool.

Optional extractors with Option

Some extractors implement an optional variant. When used inside Option, the extractor returns None instead of rejecting the request. Not every extractor supports this - only those with OptionalFromRequestParts or OptionalFromRequest implementations.

A common example is TypedHeader from the axum-extra crate. A typed header tries to parse a specific header into a Rust type. When wrapped in Option, a missing header becomes None. But if the header is present and malformed, the request is still rejected.

First, add axum-extra to your Cargo.toml.

[dependencies]
axum = "0.8"
axum-extra = { version = "0.10", features = ["typed-header"] }
tokio = { version = "1", features = ["full"] }

Then use Option<TypedHeader<UserAgent>> in a handler.

use axum::{
    routing::post,
    Router,
};
use axum_extra::{
    headers::UserAgent,
    TypedHeader,
};
async fn log_user_agent(
    user_agent: Option<TypedHeader<UserAgent>>,
) -> String {
    match user_agent {
        Some(TypedHeader(ua)) => format!("User agent: {}", ua),
        None => "No user agent provided".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/log", post(log_user_agent));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When a client sends a User-Agent header, the handler receives Some(TypedHeader(ua)). When the header is absent, it receives None. When the header is present but cannot be parsed into a UserAgent type, Axum returns 400 Bad Request. This is a subtle but useful distinction: Option handles missing data, not invalid data.

Check the extractor's docs before using Option:

Not all extractors support Option. For example, Path<T> does not make sense as Option because a route always has the path segment or it would not match. Always consult the extractor's documentation to see if it implements OptionalFromRequestParts or OptionalFromRequest.

Query parameters as optional or defaulted fields

Earlier, the Pagination struct used required fields. A missing page query parameter caused rejection. In real applications, pagination often has defaults. Axum can handle that with Serde's field attributes.

use axum::{
    extract::Query,
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    #[serde(default = "default_page")]
    page: usize,
    #[serde(default = "default_per_page")]
    per_page: usize,
}
fn default_page() -> usize { 1 }
fn default_per_page() -> usize { 10 }
async fn list_items(Query(pagination): Query<Pagination>) -> String {
    format!(
        "Showing page {}, {} items per page",
        pagination.page, pagination.per_page
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/items", get(list_items));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now, a request to /items with no query string still succeeds. The handler receives page = 1 and per_page = 10. A request to /items?page=3 gets page = 3 and the default per_page = 10. The #[serde(default = "function_name")] attribute tells Serde to call the named function when the field is absent.

You can also make fields fully optional by wrapping them in Option<T>.

#[derive(Deserialize)]
struct SearchParams {
    q: String,
    sort: Option<String>,
    limit: Option<usize>,
}

Here, q is still required. sort and limit are optional - missing values become None. This is simpler than default when there is no natural default value.

Multiple body-consuming extractors are not possible, but you can combine data

You cannot use Json<T> and String in the same handler. But you can often choose one extractor that contains everything you need. If you need both JSON and raw bytes, you can use Bytes and parse the JSON yourself. If you need JSON plus some metadata, you can deserialize the JSON into a struct that includes all the fields.

use axum::{
    extract::{Path, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateUser {
    email: String,
    age: u8,
}
async fn update_user(
    Path(user_id): Path<u32>,
    Json(update): Json<UpdateUser>,
) -> String {
    format!(
        "Updating user {} with email {} and age {}",
        user_id, update.email, update.age
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}", post(update_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This works because Path is a FromRequestParts extractor and Json is the last argument, satisfying the body-consuming rule. A request to POST /users/7 with {"email": "alice@example.com", "age": 30} gives the handler user_id = 7, update.email = "alice@example.com", and update.age = 30.

Using extractors in different route handlers

The same extractor type works across different HTTP methods. Query<T> can appear in a get handler, a post handler, or any other method. Path<T> likewise. The only rule about method applies to how the route is registered, not the extractor itself.

Here is a full main.rs showing several routes, each using extractors appropriate to the request.

use axum::{
    extract::{Path, Query, Json},
    routing::{get, post},
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
    q: String,
}
#[derive(Deserialize)]
struct CreateItem {
    name: String,
    price: f64,
}
async fn search_items(Query(params): Query<SearchParams>) -> String {
    format!("Searching for {}", params.q)
}
async fn get_item(Path(item_id): Path<u32>) -> String {
    format!("Showing item {}", item_id)
}
async fn create_item(Json(item): Json<CreateItem>) -> String {
    format!("Creating item {} priced at {}", item.name, item.price)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/search", get(search_items))
        .route("/items/{item_id}", get(get_item))
        .route("/items", post(create_item));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This application has three routes, each with a different extractor. The search_items route reads the query string. The get_item route reads the path. The create_item route reads the JSON body. Each handler has exactly the arguments it needs, and Axum handles all validation and error responses.

Debugging extractor type errors

Because extraction is type-driven, mistakes in the handler signature cause compile errors that are not always clear. A handler that puts a body extractor before a header extractor will fail with a message about the Handler trait, not about extraction order.

// This will not compile.
async fn broken_handler(
    body: String,
    headers: axum::http::HeaderMap,
) -> String {
    body
}

The error message will look similar to:

error[E0277]: the trait bound `fn(String, HeaderMap) -> ...: Handler<_, _>` is not satisfied

This tells you that the function is not a valid handler, but not why. Axum provides a debug_handler macro from the axum-macros crate that improves these errors.

Add the dependency:

[dependencies]
axum = "0.8"
axum-macros = "0.5"
tokio = { version = "1", features = ["full"] }

Then annotate the handler with #[debug_handler].

use axum_macros::debug_handler;
#[debug_handler]
async fn broken_handler(
    body: String,
    headers: axum::http::HeaderMap,
) -> String {
    body
}

Now the compiler produces a more specific error, explaining that String is a body-consuming extractor and must be the last argument. The debug_handler macro does not change runtime behavior; it only improves compile-time diagnostics.

Use debug_handler during development:

Keep #[debug_handler] on handlers while you are learning and while actively changing signatures. It costs nothing at runtime and turns confusing errors into actionable ones. You can remove it later if you prefer cleaner code.

A complete walkthrough with a Stepper

Let us build a handler step by step that uses a path extractor, a query extractor, and a JSON body extractor. This is a common pattern for update operations where the resource is identified in the path, options come from the query string, and the new data comes from the body.

1

Step 1: Define the data structures

Start with the types the handler will receive. The body type needs Deserialize from Serde. The query type also needs Deserialize.

use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateProject {
    name: String,
    description: String,
}
#[derive(Deserialize)]
struct UpdateOptions {
    notify: Option<bool>,
}
2

Step 2: Write the handler with the extractor arguments

The Path<u32> extracts the project ID, Query<UpdateOptions> extracts the query string, and Json<UpdateProject> extracts the body. The body extractor must be last.

use axum::{
    extract::{Path, Query, Json},
};
async fn update_project(
    Path(project_id): Path<u32>,
    Query(options): Query<UpdateOptions>,
    Json(project): Json<UpdateProject>,
) -> String {
    let notify = options.notify.unwrap_or(false);
    format!(
        "Updating project {} to name '{}', description '{}', notify={}",
        project_id, project.name, project.description, notify
    )
}
3

Step 3: Register the route

The route must include the {project_id} path parameter. The handler is attached to a put route because updates use PUT or PATCH.

use axum::{
    routing::put,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/projects/{project_id}", put(update_project));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
4

Step 4: Send a test request

Use curl or a similar HTTP client to send a request that exercises all three extractors.

curl -X PUT "http://127.0.0.1:3000/projects/9?notify=true" \
  -H "Content-Type: application/json" \
  -d '{"name": "Axum Guide", "description": "Learning extractors"}'

The handler responds:

Updating project 9 to name 'Axum Guide', description 'Learning extractors', notify=true

This walkthrough shows how multiple extractors combine in one handler. The path identifies the resource, the query provides optional flags, and the body carries the main payload. All three are validated by Axum before the handler runs.

The complete program from the walkthrough

The steps above showed the pieces one at a time. Here they are assembled into one file you can run as it stands.

Cargo.toml
[package]
name = "update-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
src/main.rs
use axum::{
    extract::{Path, Query, Json},
    routing::put,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateProject {
    name: String,
    description: String,
}
#[derive(Deserialize)]
struct UpdateOptions {
    notify: Option<bool>,
}
async fn update_project(
    Path(project_id): Path<u32>,
    Query(options): Query<UpdateOptions>,
    Json(project): Json<UpdateProject>,
) -> String {
    let notify = options.notify.unwrap_or(false);
    format!(
        "Updating project {} to name '{}', description '{}', notify={}",
        project_id, project.name, project.description, notify
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/projects/{project_id}", put(update_project));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run it with cargo run, then send the same curl request from step 4. A request without the ?notify=true flag still succeeds and reports notify=false, because notify is an Option<bool> in the query struct. A request with a malformed JSON body is rejected with 400 Bad Request before the handler runs, and a request to /projects/abc is rejected the same way, because abc cannot be parsed as a u32.

Building a custom extractor for repeated logic

Sometimes you need the same extraction logic in many handlers. Instead of duplicating it, you can create your own extractor. A custom extractor implements FromRequestParts if it needs only the request head, or FromRequest if it needs the body.

Here is a custom extractor that reads the User-Agent header and rejects the request if the header is missing.

use axum::{
    extract::FromRequestParts,
    http::{
        header::{HeaderValue, USER_AGENT},
        request::Parts,
        StatusCode,
    },
    routing::get,
    Router,
};
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"))
        }
    }
}
async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) -> String {
    format!("User agent: {}", user_agent.to_str().unwrap_or("invalid"))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/whoami", get(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The impl<S> FromRequestParts<S> block defines how the extractor works. The from_request_parts method receives the request head and returns either Ok(ExtractUserAgent(...)) or Err((StatusCode, "message")). The rejection type is a tuple of status code and message, which Axum knows how to convert into an HTTP response.

This extractor does not consume the body, so it implements FromRequestParts. It can be used alongside other FromRequestParts extractors, as long as a body extractor is last.

Custom extractors that consume the body

If your custom logic needs to read the request body, implement FromRequest instead. This is more involved because FromRequest has more associated types and takes the full Request.

use axum::{
    body::Bytes,
    extract::{FromRequest, Request},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
struct ValidatedBody(Bytes);
impl<S> FromRequest<S> for ValidatedBody
where
    Bytes: FromRequest<S>,
    S: Send + Sync,
{
    type Rejection = Response;
    async fn from_request(
        req: Request,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        let bytes = Bytes::from_request(req, state)
            .await
            .map_err(|err| err.into_response())?;
        if bytes.is_empty() {
            return Err((
                StatusCode::BAD_REQUEST,
                "Request body must not be empty",
            )
                .into_response());
        }
        Ok(ValidatedBody(bytes))
    }
}
async fn handler(ValidatedBody(bytes): ValidatedBody) -> String {
    format!("Received {} bytes", bytes.len())
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/validate", post(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Inside from_request, the custom extractor delegates to the built-in Bytes extractor by calling Bytes::from_request(req, state). This reads the entire body. Then it checks whether the body is empty and rejects it if so. The rejection type is Response, which gives full control over the error. The ValidatedBody(Bytes) tuple wraps the extracted bytes so the custom type is distinct from Bytes.

Delegate, do not reimplement:

When building a body-consuming custom extractor, delegate to a built-in extractor like Bytes or Json instead of manually reading the body stream. The built-in extractors handle buffering, size limits, and error conversion. Reimplementing that yourself is error-prone.

What can go wrong and how to recognize it

Beginner mistakes with extractor arguments are predictable. Knowing them in advance will save hours of confusing errors.

Putting the body extractor before other extractors. This is the most common compile error. The signature async fn handler(body: String, headers: HeaderMap) fails because String is a body consumer and must be last. The fix is to reorder arguments.

Forgetting that Query<T> fields are required by default. A handler expecting Query<Pagination> will reject requests that lack page or per_page. The fix is to use Option<T> fields or Serde default attributes.

Trying to use two body extractors. This does not compile. If you need both raw bytes and parsed JSON, either parse the JSON yourself from Bytes or change the design so only one body extractor is needed.

Using Option with an extractor that does not support it. Not every extractor has an optional variant. Path<T> inside Option will not work as expected. Check the documentation for OptionalFromRequestParts or OptionalFromRequest.

Misunderstanding rejection behavior. When an extractor fails, the handler does not run. If you need the handler to run regardless, wrap the extractor in Result.

Reordering is not optional:

If you are coming from languages where function argument order is arbitrary, this rule may surprise you. In Axum, the request body extractor must be the final argument. Rust's compiler will enforce it, but the error message can be cryptic. Use #[debug_handler] from axum-macros to get a clear explanation.

Comparing extractor arguments to manual parsing

To appreciate what extractors do, here is the same job done by hand inside a real Axum handler that takes the whole Request and parses the path itself.

use axum::{
    extract::Request,
    routing::get,
    Router,
};
async fn manual_get_user(request: Request) -> String {
    let path = request.uri().path(); // "/users/42"
    let segments: Vec<&str> = path.split('/').collect();
    let id_str = segments.get(2);
    match id_str {
        Some(id_str) => match id_str.parse::<u32>() {
            Ok(id) => format!("User {}", id),
            Err(_) => "Bad request".to_string(),
        },
        None => "Bad request".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(manual_get_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Register it with .route("/users/{id}", get(manual_get_user)) and a request to /users/42 returns User 42, while /users/hello returns Bad request with a 200 status, because the handler itself decided what to send back instead of Axum rejecting the request. That last detail is the giveaway: the manual version has to invent its own error handling, and it gets the status code wrong, while the extractor version rejects with a proper 400 before the handler ever runs.

Now compare that to the Axum version:

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

The Axum version is shorter, clearer, and free of manual error handling. The path parsing, integer conversion, and rejection logic all happen in the extractor. This is the core benefit: every handler gets robust, consistent extraction without writing repetitive parsing code.

When to use which extractor

The choice of extractor follows from where the data lives in the HTTP request.

  • Data in the URL path → Path<T>
  • Data in the query string → Query<T>
  • Data in HTTP headers → HeaderMap or TypedHeader<T>
  • Data in the request body as raw text → String or Bytes
  • Data in the request body as JSON → Json<T>
  • Data added by middleware → Extension<T>
  • Shared application data → State<T>
  • Need the entire request → Request

For most CRUD applications, the common combinations are Path<T> plus Json<T> for updates and deletes, Query<T> for list endpoints with filtering and pagination, and Json<T> alone for create endpoints.

Summary

Extractor arguments are the mechanism through which Axum handlers declare their input. Each argument's type tells Axum what part of the request to extract - path, query, header, body, or state. Axum runs extractors left to right, validates each one, and only calls the handler if all succeed.

The most important rule is that the request body can be consumed once, so body-consuming extractors must be the last argument. This constraint is enforced at compile time, and #[debug_handler] makes violations easier to understand. When extraction fails, the default behavior is an automatic error response. For more control, wrap an extractor in Result<T, T::Rejection> and handle the rejection explicitly.

Extractors keep handlers focused. Instead of parsing requests by hand, you declare what you need and let Axum do the preparation. This is the foundation on which all practical Axum handlers are built.