Multi-argument handlers

Learn how to define Axum handlers that accept multiple extractor arguments and combine path segments, query parameters, state, and request bodies in one function

Most web requests carry more than one piece of information. A URL includes a path, often a query string, headers, and sometimes a JSON body. A handler that can only work with zero inputs would force you to manually dig through the request object for every single value. Axum solves this by letting a handler accept multiple arguments, where each argument is an extractor that pulls one specific piece of data out of the incoming request.

What a multi-argument handler looks like

A zero-argument handler, which you have already seen, is just an async fn with no parameters. A multi-argument handler is the same idea, but the function signature lists two, three, or more parameters. Each parameter has a type that Axum knows how to extract from the request.

Here is the smallest possible example that takes two arguments: a path parameter and a query parameter.

use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
}
async fn show_user(
    Path(user_id): Path<u32>,
    Query(pagination): Query<Pagination>,
) -> String {
    format!(
        "Showing user {} with page {:?}",
        user_id,
        pagination.page.unwrap_or(1)
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{user_id}", get(show_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When a request arrives at /users/42?page=3, Axum looks at the handler signature. It sees two parameters: Path<u32> and Query<Pagination>. It extracts the number 42 from the path segment {user_id} and builds a Pagination struct from the query string. The handler then receives both values and formats a response string.

Notice the pattern: each extractor type is wrapped in a tuple-like pattern inside the function arguments. Path(user_id): Path<u32> says "take the Path<u32> extractor, run it, and give me the inner u32 value under the name user_id." You could also write path: Path<u32> and then access path.0 inside the function, but destructuring directly in the signature is the common idiomatic style.

Why handlers accept many arguments instead of one request object

Before extractors, web frameworks often handed you a single Request object and expected you to parse everything yourself. That works, but it leads to repetitive boilerplate. Every handler that needs a user ID from the URL has to write the same parsing code. It also makes the handler's requirements less visible.

Axum's argument list is a declaration of what the handler needs. If a handler requires a database connection and a user ID, you write those as parameters. Axum will either provide them or return an error response before your handler body runs. This keeps application logic focused on business rules rather than request plumbing.

Think of extractors as a vending machine. You press the button for a snack and the machine gives you that snack. You do not open the machine, find the snack manually, and then close it. Multi-argument handlers are you pressing several buttons at once and receiving all the snacks in order.

The basic rule for combining extractors

Axum has two families of extractor traits: FromRequestParts and FromRequest. FromRequestParts works on the request head, which includes the method, URI, headers, and extensions. It does not consume the request body. FromRequest can read the entire request, including the body, but because the body is a stream that can only be consumed once, it must be the last argument.

All arguments except the last must implement FromRequestParts. The last argument may implement FromRequest, and at most one argument in the whole handler may do so. A handler with no body extractor is perfectly fine - then the last argument is a FromRequestParts extractor like the rest. This is a hard rule. If you put a body extractor like Json<T> before a parts extractor like Query<T>, Axum will refuse to compile your handler.

Here is a valid combination: Path, Query, then Json.

use axum::{
    extract::{Path, Query, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Filters {
    sort: Option<String>,
}
#[derive(Deserialize)]
struct NewItem {
    name: String,
    price: f64,
}
async fn create_item(
    Path(category_id): Path<u32>,
    Query(filters): Query<Filters>,
    Json(new_item): Json<NewItem>,
) -> String {
    format!(
        "Creating item '{}' in category {} with sort {:?}",
        new_item.name,
        category_id,
        filters.sort
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/categories/{category_id}/items", post(create_item));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This handler receives a path segment, a query string, and a JSON body. The order is correct: two FromRequestParts extractors first, then one FromRequest extractor last. Axum executes them in order and your function runs only after all three succeed. If the JSON body is malformed, Axum returns a 400 Bad Request and the function body never executes.

Order matters:

Always place extractors that implement FromRequestParts before the extractor that implements FromRequest. Putting Json or Bytes before Query or Path causes a compile-time error because the body would be consumed before the parts extractor can run.

How to know which extractor goes where

You do not have to memorize every extractor's trait implementation. Axum's documentation for each extractor type tells you which trait it implements. Most common extractors fall into a predictable pattern.

Extractors that only need the head of the request are FromRequestParts. These include:

  • Path<T>
  • Query<T>
  • HeaderMap
  • Extension<T>
  • State<T>
  • Method
  • Uri
  • OriginalUri

Extractors that need to read the body are FromRequest. These include:

  • Json<T>
  • Form<T>
  • Bytes
  • String
  • Request<Body>

The last argument reads the body:

Because the request body is a stream, it can only be read once. Axum therefore allows at most one FromRequest extractor, and if one is present it must be the last argument. A handler with no body extractor at all is perfectly fine. You cannot have two body extractors in one handler; if you need both JSON and raw bytes, use Bytes and parse the JSON yourself.

Starting with two arguments - a complete runnable app

Let's build a minimal application from scratch that serves a greeting message with a path parameter and a query parameter. This is the most common multi-argument scenario.

// main.rs
use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct GreetingParams {
    name: Option<String>,
}
async fn greet(
    Path(language): Path<String>,
    Query(params): Query<GreetingParams>,
) -> String {
    let greeting = match language.as_str() {
        "en" => "Hello",
        "es" => "Hola",
        "fr" => "Bonjour",
        _ => "Hi",
    };
    let name = params.name.unwrap_or_else(|| "stranger".to_string());
    format!("{}, {}!", greeting, name)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/greet/{language}", get(greet));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run this with cargo run and open these URLs in a browser or with curl:

  • http://127.0.0.1:3000/greet/en?name=Alice returns Hello, Alice!
  • http://127.0.0.1:3000/greet/es returns Hola, stranger!
  • http://127.0.0.1:3000/greet/de?name=Max returns Hi, Max!

The handler receives both the language from the URL path and the optional name from the query string. Axum parses them before the handler runs. If the query string is missing name, the Option<String> is None, and the handler falls back to "stranger".

The Path and Query extractors both implement FromRequestParts. Their order does not matter relative to each other, but both must appear before any body extractor. You could swap them and the handler would still work: Query(params): Query<GreetingParams>, Path(language): Path<String> is equally valid.

Adding application state as a third argument

In a real application, you often need shared state like a database pool or configuration. Axum provides the State extractor for this. State also implements FromRequestParts, so it can appear anywhere among the parts extractors, usually first for readability.

use axum::{
    extract::{Path, Query, State},
    routing::get,
    Router,
};
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    greetings: Arc<HashMap<String, String>>,
}
#[derive(Deserialize)]
struct GreetingParams {
    name: Option<String>,
}
async fn greet_with_state(
    State(state): State<AppState>,
    Path(language): Path<String>,
    Query(params): Query<GreetingParams>,
) -> String {
    let greeting = state
        .greetings
        .get(&language)
        .cloned()
        .unwrap_or_else(|| "Hi".to_string());
    let name = params.name.unwrap_or_else(|| "stranger".to_string());
    format!("{}, {}!", greeting, name)
}
#[tokio::main]
async fn main() {
    let mut greetings = HashMap::new();
    greetings.insert("en".to_string(), "Hello".to_string());
    greetings.insert("es".to_string(), "Hola".to_string());
    greetings.insert("fr".to_string(), "Bonjour".to_string());
    let state = AppState {
        greetings: Arc::new(greetings),
    };
    let app = Router::new()
        .route("/greet/{language}", get(greet_with_state))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now the handler has three arguments: State, Path, and Query. All three are FromRequestParts, so the last-argument rule still holds. The State extractor looks up the AppState from the router's state storage, which you attach with .with_state(). The handler then uses the language from the path to look up the correct greeting in the shared map.

Three parts extractors are fine:

You can have as many FromRequestParts extractors as you need, up to the total limit of 16 arguments. They can appear in any order relative to each other; only the body extractor must be last.

Combining a body extractor with state and path

The real power of multi-argument handlers shows when you mix parts extractors with a body extractor. A typical POST handler receives a path parameter, shared state, and a JSON body.

use axum::{
    extract::{Path, State, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
use std::sync::Mutex;
#[derive(Clone)]
struct AppState {
    next_id: std::sync::Arc<Mutex<u32>>,
}
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}
async fn create_user(
    State(state): State<AppState>,
    Path(team_id): Path<u32>,
    Json(payload): Json<CreateUser>,
) -> String {
    let mut id = state.next_id.lock().unwrap();
    *id += 1;
    let new_user_id = *id;
    format!(
        "Created user {} (id {}) in team {}",
        payload.name, new_user_id, team_id
    )
}
#[tokio::main]
async fn main() {
    let state = AppState {
        next_id: std::sync::Arc::new(Mutex::new(0)),
    };
    let app = Router::new()
        .route("/teams/{team_id}/users", post(create_user))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test it with:

curl -X POST http://127.0.0.1:3000/teams/7/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","email":"alice@example.com"}'

Response: Created user Alice (id 1) in team 7

The arguments are State<AppState>, Path<u32>, and Json<CreateUser>. The first two are FromRequestParts, the last is FromRequest. This is exactly the required order. Axum extracts the state, parses 7 from the path, and then reads the JSON body. Only then does your function run.

Using tuple destructuring for readability

Each extractor can be destructured in the function signature. You can give the inner value any name you want. For example, instead of Path(team_id): Path<u32> you could write path: Path<u32> and later use path.0. Destructuring keeps the signature clean and the variable name local.

Here is the same handler without destructuring, to contrast:

async fn create_user_raw(
    state: State<AppState>,
    path: Path<u32>,
    json: Json<CreateUser>,
) -> String {
    let team_id = path.0;
    let payload = json.0;
    let mut id = state.0.next_id.lock().unwrap();
    *id += 1;
    let new_user_id = *id;
    format!(
        "Created user {} (id {}) in team {}",
        payload.name, new_user_id, team_id
    )
}

Both versions compile and behave identically. The destructured version is more readable because the variable names appear in the function signature and the handler body uses them directly. The non-destructured version requires you to remember that Path<u32> holds its value in field .0, and State<AppState> also in .0. For simple types, destructuring is the recommended style.

Destructuring is optional but idiomatic:

The tuple-like pattern Path(user_id): Path<u32> is not required by Axum. It is Rust pattern matching that unpacks the extractor's inner value. You can choose whichever style your team finds clearer. Consistency matters more than the choice itself.

What happens when extraction fails

Every extractor can return an error. If a path parameter is missing or cannot be parsed as the expected type, Path<T> returns a rejection. If the query string is malformed or missing required fields, Query<T> returns a rejection. If the JSON body is invalid, Json<T> returns a rejection. In all these cases, Axum converts the rejection into an HTTP response and your handler function never runs.

Consider this handler with three extractors, one of which can fail. (Pagination and CreateUser are the structs from the earlier examples on this page.)

use axum::extract::{Json, Path, Query};
async fn example(
    Path(id): Path<u32>,
    Query(params): Query<Pagination>,
    Json(body): Json<CreateUser>,
) -> String {
    format!("user {} page {:?} named {}", id, params.page, body.name)
}

If a request arrives with /users/not-a-number, the Path<u32> extractor fails. Axum returns 400 Bad Request and the function body is skipped. (A 404 only happens when no route matches the path at all.) You do not need to write any error-handling code in the handler for extractor failures; Axum does it for you.

This behavior is both convenient and limiting. Convenient because you can assume all arguments are valid inside the function. Limiting because you cannot customize the error response for extraction failures without writing a custom extractor. For most applications, the default error responses are acceptable.

Missing required query fields cause 400:

If your Query<T> struct has a required field like page: u32 but the request does not include ?page=, the extractor fails and the handler is never called. If you want the field to be optional, use Option<u32>. If you want a default value, handle it inside the handler after extraction.

Multiple ways to get the same information

Axum often provides several extractor types that can access similar data. For query parameters, you could use Query<T> with a deserializable struct, or you could use RawQuery to get the entire query string as an Option<String>, or you could use OriginalUri and parse it manually. The choice depends on how structured your query parameters are.

For headers, you could use HeaderMap to access all headers, or TypedHeader to extract a single typed header. For request data, you could use Extension<T> for middleware-injected values or State<T> for router-wide state. Each has its own purpose.

Here is a handler that receives the same query parameters both structured and raw, just to illustrate the difference:

use axum::{
    extract::{Query, RawQuery},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
    q: String,
    limit: Option<u32>,
}
async fn search(
    Query(params): Query<SearchParams>,
    RawQuery(raw): RawQuery,
) -> String {
    format!(
        "Structured query: q={}, limit={:?}. Raw query: {:?}",
        params.q, params.limit, raw
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/search", get(search));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /search?q=rust&limit=10 produces:

Structured query: q=rust, limit=Some(10). Raw query: Some("q=rust&limit=10")

The Query<SearchParams> extractor parses the query string into fields. The RawQuery extractor just hands you the unparsed string. Both implement FromRequestParts, so their order is flexible. This example shows that multiple extractors can read overlapping parts of the request without conflict, as long as they only touch the head and not the body.

Combining path parameters with a custom extractor

Sometimes you have data that does not fit a built-in extractor. You can write your own struct that implements FromRequestParts and then use it as an argument alongside other extractors. A short example demonstrates how it fits into a multi-argument handler.

Assume you have a UserAgent extractor that pulls the User-Agent header:

use axum::{
    extract::{FromRequestParts, Path},
    http::request::Parts,
    routing::get,
    Router,
};
use std::future::Future;
struct UserAgent(String);
impl<S> FromRequestParts<S> for UserAgent
where
    S: Send + Sync,
{
    type Rejection = ();
    fn from_request_parts(parts: &mut Parts, _state: &S) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
        let ua = parts
            .headers
            .get("user-agent")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("unknown")
            .to_string();
        async move { Ok(UserAgent(ua)) }
    }
}
async fn show_client(
    UserAgent(ua): UserAgent,
    Path(user_id): Path<u32>,
) -> String {
    format!("User {} accessed from {}", user_id, ua)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{user_id}", get(show_client));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Note that from_request_parts is an ordinary function returning impl Future - it is not an async fn, and Axum does not re-export async_trait, so #[async_trait] does not work here. The custom UserAgent struct implements FromRequestParts, so it can appear anywhere before the last body extractor. In this handler there is no body extractor, so the last argument is also a parts extractor. Axum sees two parts extractors and is happy.

The 16-argument limit and why it exists

Axum's Handler trait has blanket implementations for async functions with up to 16 arguments. This is not an arbitrary number; it comes from the way Rust's macro system and trait implementations are written. Each arity needs its own impl. Supporting more than 16 would require generating more code and is rarely needed.

In practice, a handler with more than four or five arguments is a sign that you might need to group related data into a single extractor struct. For example, instead of taking State, Path, Query, HeaderMap, Extension, and Json all separately, you could define a custom extractor that bundles the parts you need and implements FromRequestParts or FromRequest once. That keeps the handler signature readable and reduces the chance of argument-order mistakes.

Stay well below 16 arguments:

While Axum technically supports up to 16 arguments, a handler with many arguments is hard to read and test. If you find yourself approaching that limit, extract a custom extractor that groups related request data. Your future self will thank you.

Common compile errors and how to read them

When you write a handler that violates the extractor rules, Rust's error message can be confusing because it points at the get(...) or post(...) call and says something like "the trait Handler<_, _> is not implemented". It does not directly tell you which argument is wrong.

Consider this incorrect handler that puts Json before Query:

use axum::{
    extract::{Json, Query},
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Filter {
    active: bool,
}
#[derive(Deserialize)]
struct Payload {
    name: String,
}
async fn wrong_order(
    Json(payload): Json<Payload>,
    Query(filter): Query<Filter>,
) -> String {
    format!("{} {}", payload.name, filter.active)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/items", post(wrong_order));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This will not compile. The error message will mention that Handler is not implemented for this function, but it will not clearly say "Json must be last". To get a better error, you can use the debug_handler macro from axum-macros. Add the dependency and annotate your handler:

use axum_macros::debug_handler;
#[debug_handler]
async fn wrong_order(
    Json(payload): Json<Payload>,
    Query(filter): Query<Filter>,
) -> String {
    format!("{} {}", payload.name, filter.active)
}

The macro expands to extra type checks that produce a more specific error, often naming the offending argument and the trait requirement. This is invaluable when you are learning.

Use debug_handler when stuck:

If you see a confusing Handler trait error, add #[debug_handler] from the axum-macros crate to your handler temporarily. It will give you a much clearer message about which argument does not implement the required trait. Remove it in production if you want to avoid the macro dependency, or keep it as documentation.

Handling closures as handlers

So far we have used named async functions. Axum also accepts closures as handlers. The rules are slightly different because closures must implement Clone + Send + Sync + 'static, and they cannot easily use the debug_handler macro. But the argument rules are identical.

Here is the same multi-argument handler written as a closure:

use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Params {
    verbose: Option<bool>,
}
#[tokio::main]
async fn main() {
    let app = Router::new().route(
        "/users/{id}",
        get(|Path(id): Path<u32>, Query(params): Query<Params>| async move {
            if params.verbose.unwrap_or(false) {
                format!("User {} (verbose)", id)
            } else {
                format!("User {}", id)
            }
        }),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The closure takes the same extractor arguments and returns an async block. Because it is a closure, it automatically implements Clone only if all captured variables are Clone. Since we capture nothing here, it is fine. If you capture a value, it must be Clone so the router can clone the handler, and it must be 'static - capturing by reference does not work because the reference would not live long enough. For simple cases, closures are convenient for short handlers; named functions are better for larger logic.

When a handler expects many query parameters, you can group them into a single Query<T> struct rather than extracting each one separately. This keeps the argument count low and makes the struct reusable across handlers.

use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct ListParams {
    page: Option<u32>,
    per_page: Option<u32>,
    sort_by: Option<String>,
    order: Option<String>,
    search: Option<String>,
}
async fn list_users(
    Path(team_id): Path<u32>,
    Query(params): Query<ListParams>,
) -> String {
    let page = params.page.unwrap_or(1);
    let per_page = params.per_page.unwrap_or(20);
    let search = params.search.unwrap_or_default();
    format!(
        "Listing users for team {}: page {}, per_page {}, search '{}'",
        team_id, page, per_page, search
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/teams/{team_id}/users", get(list_users));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This handler takes only two arguments but receives five potential query parameters. The ListParams struct defines all of them as optional. Inside the handler, you apply defaults. This is much cleaner than five separate Query<Option<u32>> arguments, and it keeps the function signature readable.

Combining extractors in different orders for parts extractors

The order of FromRequestParts extractors relative to each other does not affect functionality. Axum processes them independently. Some developers prefer to put State first because it represents application dependencies. Others put Path first because it identifies the resource. The choice is stylistic, but be consistent across your codebase.

use axum::extract::{Path, Query, State};
use serde::Deserialize;
#[derive(Clone)]
struct AppState;
#[derive(Deserialize)]
struct Params {
    verbose: Option<bool>,
}
// Style A: State first
async fn get_item_a(
    State(_state): State<AppState>,
    Path(id): Path<u32>,
    Query(params): Query<Params>,
) -> String {
    format!("Item {} (verbose: {:?})", id, params.verbose)
}
// Style B: Path first
async fn get_item_b(
    Path(id): Path<u32>,
    State(_state): State<AppState>,
    Query(params): Query<Params>,
) -> String {
    format!("Item {} (verbose: {:?})", id, params.verbose)
}

Both compile and work. The important rule is that any body extractor must be last. Parts extractors can be in any order.

Pick an order and stick with it:

Consistency in argument order makes your codebase easier to scan. A common convention is State first, then Path, then Query, then headers, then body. However, teams can choose their own. The compiler only enforces that the body extractor is last.

Using multiple path parameters

A route can contain several path segments, but each Path<T> extractor deserializes the whole set of captures, not one segment. So you cannot extract them individually with multiple Path<T> arguments - two Path<u32> arguments on a two-segment route fail at runtime with a 500 ("Wrong number of path arguments for Path. Expected 1 but got 2. Note that multiple parameters must be extracted with a tuple Path<(_, _)> or a struct Path<YourParams>"). Instead, use a single Path<(T1, T2, ...)> tuple or a Path<YourParams> struct:

use axum::{extract::Path, routing::get, Router};
async fn show_team_member(
    Path((team_id, member_id)): Path<(u32, u32)>,
) -> String {
    format!("Team {}, member {}", team_id, member_id)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route(
        "/teams/{team_id}/members/{member_id}",
        get(show_team_member),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The tuple assigns captures in order: the first element gets the first capture, the second gets the second. For a named, self-documenting version, define a struct with fields named after the placeholders (team_id, member_id) and use Path<YourParams> - struct fields must match the placeholder names exactly.

One Path extractor per handler:

Do not use two Path<T> extractors in one handler - the second one fails at runtime with a 500. Bind all captures at once with a single Path<(T1, T2, ...)> tuple or a Path<YourParams> struct, as shown above.

Extracting state and multiple body extractors is not allowed

Axum does not allow two body extractors in one handler. This is because the request body can only be consumed once. If you need to read the raw body and also parse JSON, you must choose one approach. You can read Bytes and then parse it yourself, or you can use Json and then serialize back to bytes if needed. But you cannot have both Json<T> and Bytes as separate arguments.

Here is an invalid handler:

async fn invalid(
    Json(payload): Json<CreateUser>,
    Bytes(raw): Bytes,
) -> String {
    // This will not compile
}

The compiler reports the usual error that the Handler trait is not implemented for this function. The underlying cause is the extractor rule: Axum's Handler implementation requires every argument except the last to implement FromRequestParts, so a handler with two body extractors cannot satisfy it.

If you need both, the solution is to use one Bytes extractor and parse the JSON manually using serde_json:

use axum::{
    body::Bytes,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    name: String,
}
async fn raw_and_parsed(
    raw: Bytes,
) -> String {
    let parsed: CreateUser = serde_json::from_slice(&raw).unwrap_or(CreateUser { name: "unknown".into() });
    format!("Raw bytes length: {}, parsed name: {}", raw.len(), parsed.name)
}

This handler has one argument, which is a body extractor (Bytes). It does its own parsing. The point is that multiple body extractors are impossible; choose one and handle the rest manually.

When to combine arguments vs create a custom extractor

As your handlers grow, you may find the same set of extractors repeated across many endpoints. For example, several endpoints in your API might require State<AppState>, Path<tenant_id>, and HeaderMap. Instead of repeating those three arguments everywhere, you can define a custom extractor struct that bundles them and implements FromRequestParts. Then each handler takes just that one extractor.

use axum::{
    extract::{FromRequestParts, Path},
    http::{request::Parts, HeaderMap},
};
use std::future::Future;
#[derive(Clone)]
struct AppState;
struct RequestContext {
    state: AppState,
    tenant_id: u32,
    headers: HeaderMap,
}
impl FromRequestParts<AppState> for RequestContext {
    type Rejection = ();
    fn from_request_parts(parts: &mut Parts, state: &AppState) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
        let state = state.clone();
        let headers = parts.headers.clone();
        async move {
            let Path(tenant_id) = Path::<u32>::from_request_parts(parts, &state).await.map_err(|_| ())?;
            Ok(RequestContext {
                state,
                tenant_id,
                headers,
            })
        }
    }
}
async fn get_tenant_data(ctx: RequestContext) -> String {
    format!("Tenant {} has {} headers", ctx.tenant_id, ctx.headers.len())
}

Two things to notice here. First, the implementation is for the concrete state type (FromRequestParts<AppState>), not a generic S: a generic &S cannot be turned into an AppState, so state.clone() would give you &S instead of the owned state the struct needs. Second, like the UserAgent example above, from_request_parts is an ordinary function returning impl Future, not an async fn - #[async_trait] does not apply to this trait.

This is a more advanced pattern, but it demonstrates that multi-argument handlers are not the only way to organize complex request data. Axum's extractor system is composable; you can build higher-level extractors from lower-level ones and then use just one argument.

Custom extractors reduce argument clutter:

If you see the same three or four extractors repeated across many handlers, that is a signal to create a custom extractor. It centralizes the extraction logic and makes each handler's signature trivial. However, for simple cases with two or three arguments, multiple arguments are perfectly fine and easier to read.

A complete example with state, path, query, and JSON

Let's put everything together into one realistic handler that handles a PATCH request to update a user's profile. It takes state for a database-like map, a path parameter for user ID, a query parameter for returning full details, and a JSON body with the fields to update.

use axum::{
    extract::{Path, Query, State, Json},
    routing::patch,
    Router,
};
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    users: Arc<Mutex<HashMap<u32, User>>>,
}
#[derive(Clone)]
struct User {
    name: String,
    email: String,
}
#[derive(Deserialize)]
struct UpdateUser {
    name: Option<String>,
    email: Option<String>,
}
#[derive(Deserialize)]
struct Options {
    verbose: Option<bool>,
}
async fn update_user(
    State(state): State<AppState>,
    Path(user_id): Path<u32>,
    Query(options): Query<Options>,
    Json(update): Json<UpdateUser>,
) -> String {
    let mut users = state.users.lock().unwrap();
    if let Some(user) = users.get_mut(&user_id) {
        if let Some(name) = update.name {
            user.name = name;
        }
        if let Some(email) = update.email {
            user.email = email;
        }
        if options.verbose.unwrap_or(false) {
            format!("Updated user {}: name={}, email={}", user_id, user.name, user.email)
        } else {
            format!("Updated user {}", user_id)
        }
    } else {
        format!("User {} not found", user_id)
    }
}
#[tokio::main]
async fn main() {
    let mut users = HashMap::new();
    users.insert(1, User { name: "Alice".into(), email: "alice@example.com".into() });
    users.insert(2, User { name: "Bob".into(), email: "bob@example.com".into() });
    let state = AppState {
        users: Arc::new(Mutex::new(users)),
    };
    let app = Router::new()
        .route("/users/{user_id}", patch(update_user))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test with:

curl -X PATCH http://127.0.0.1:3000/users/1?verbose=true \
  -H "Content-Type: application/json" \
  -d '{"name":"Alicia"}'

Response: Updated user 1: name=Alicia, email=alice@example.com

This handler has four arguments in the correct order: three FromRequestParts extractors followed by one FromRequest extractor. It demonstrates how multiple pieces of request data come together cleanly in one function.

Summary

Multi-argument handlers are the natural evolution from zero-argument handlers. They let Axum's extractor system deliver exactly the data your handler needs, with no manual parsing. The core rule is simple: all arguments except the last must implement FromRequestParts, and at most one argument - the last one - may implement FromRequest. This ensures the request body is only read once. You can combine Path, Query, State, HeaderMap, Extension, and other parts extractors in any order, then add a single body extractor at the end.

The most important takeaway is that the argument list is a declaration. It tells Axum what your handler needs, and Axum either provides it or returns an error before your code runs. This shifts validation and parsing out of the handler body, making your application logic smaller and more focused. When you find yourself repeating the same extractors across many handlers, consider grouping them into a custom extractor struct. That pattern builds on the same foundation and keeps your codebase maintainable as it grows.