Extractor Order Rules

Learn how the order of extractor parameters in an Axum handler controls execution order, why body-consuming extractors must always be last, and how to structure handler signatures correctly.

When a handler receives multiple extractors, Axum runs them one after another in a predictable sequence: left to right, matching the order they appear in your function signature. That rule alone shapes how you write every handler with more than one input. A second, stricter rule sits on top of it - any extractor that reads the request body must be the final parameter, and there can only be one of them. This page explains both rules, shows what happens when you break them, and gives you a mental model that makes handler signatures easy to reason about.

What extractor order actually means

Every argument in an Axum handler is an extractor. When a request arrives, Axum goes through your parameters one by one, from the leftmost to the rightmost, and runs each extractor's logic before moving to the next. If the first extractor fails, the second one never runs. If the second fails, the third never runs, and so on.

This matters for two reasons. First, some extractors read from parts of the request that other extractors don't touch, so the practical difference is small. Second, some extractors have side effects or depend on state that earlier extractors might change. Knowing that execution follows parameter order tells you exactly what happens at runtime when a request comes in.

Here is the simplest way to see the rule in action. Look at this handler:

use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: usize,
    per_page: usize,
}
async fn get_user_things(
    Path(user_id): Path<u32>,
    Query(pagination): Query<Pagination>,
) -> String {
    format!(
        "User {} requested page {} with {} items per page",
        user_id, pagination.page, pagination.per_page
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}/things", get(get_user_things));
    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();
}

When a request like GET /users/42/things?page=3&per_page=20 arrives, Axum first runs the Path<u32> extractor. It reads the {user_id} segment from the URL, parses it as a u32, and stores the value. Only after that succeeds does Axum run the Query<Pagination> extractor, which reads the query string and deserializes it into the Pagination struct. The handler then formats a string using both values.

Order matches your signature:

If you run this code and send the request shown above, the response body will be User 42 requested page 3 with 20 items per page. That confirms both extractors ran in the exact order they appear in the function parameters.

This left-to-right rule holds for every extractor in Axum, not just Path and Query. The next sections build on this foundation and introduce the constraint that makes the rule feel stricter.

The body-consuming extractor rule

The request body is a stream of bytes that Axum can hand to your handler exactly once. Once an extractor reads from that stream, the data is gone, with no rewinding and no second pass. That is why the compiler refuses any handler that would read the body twice, instead of letting the second read fail at runtime.

Because of this, Axum enforces a hard rule: only one extractor in a handler may consume the request body, and that extractor must be the last parameter. The rule is enforced by the compiler, not at runtime: a handler that breaks it simply does not compile, so the double-read situation can never reach a running server.

Think of it like a checkout line at a grocery store. The cashier takes items from your cart one at a time. Once an item has been scanned and bagged, it is gone from the cart. You cannot scan the same item twice, and you certainly cannot scan two different items that are actually the same physical object. The request body is the item - it can only be handed to one extractor, one time.

Some extractors read the body: Json, Form, String, Bytes, Request. Others only read metadata - the URL path, query string, headers, method, and application state. Those metadata extractors don't touch the body at all, so they can appear anywhere in the parameter list. But the moment you include a body-consuming extractor, it must sit at the far right end of your parameter list.

Here is a valid handler that mixes metadata extractors with a body extractor:

use axum::{
    extract::{Path, Query, State},
    http::Method,
    Json,
    routing::put,
    Router,
};
use serde::Deserialize;
#[derive(Clone)]
struct AppState {
    db_name: String,
}
#[derive(Deserialize)]
struct UpdatePayload {
    name: String,
    active: bool,
}
async fn update_user(
    method: Method,
    Path(user_id): Path<u32>,
    State(state): State<AppState>,
    Json(payload): Json<UpdatePayload>,
) -> String {
    format!(
        "{} request to update user {} in database {} - new name: {}, active: {}",
        method, user_id, state.db_name, payload.name, payload.active
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}", put(update_user))
        .with_state(AppState {
            db_name: "production_users".to_string(),
        });
    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();
}

The order here is Method, then Path, then State, then Json. Method reads the HTTP method from the request head. Path reads the URL segment. State pulls data from application state. None of those consume the body. Json reads the body and deserializes it, so it sits last. If you moved Json before any of the other parameters, the compiler would refuse to build your program.

The reason Axum knows the difference is the trait system. Metadata extractors implement FromRequestParts, which gives them access only to the request head - the method, URI, headers, and extensions - but not the body. Body-consuming extractors implement FromRequest, which receives the entire request including the body stream. Axum requires every parameter except the last to implement FromRequestParts, and the last parameter to implement FromRequest. The compiler enforces this through trait bounds, which is why the error shows up at compile time rather than at runtime.

What the compile error looks like

When you place a body-consuming extractor in the wrong position, the error message can look intimidating at first. But the core problem is always the same: you put a FromRequest extractor where Axum expected a FromRequestParts extractor.

Here is an incorrect example that produces a compile error:

use axum::http::Method;
// This will not compile.
async fn handler(
    body: String,
    method: Method,
) {
    // ...
}

The compiler output includes a message similar to the trait bound String: FromRequestParts<S> is not satisfied. What that really says is: "You told Axum to treat String as a metadata extractor by placing it before the last parameter, but String reads the body, so it can only implement FromRequest, not FromRequestParts."

This is a compile-time error, not a runtime one:

A body extractor in the wrong position will never reach a running server. The Rust compiler stops the build and tells you the trait bound is not satisfied. The fix is always to reorder the parameters so the body-consuming extractor is last.

The same error appears if you try to use two body extractors in the same handler:

use axum::Json;
use serde::Deserialize;
#[derive(Deserialize)]
struct Payload {}
// This will not compile.
async fn handler(
    string_body: String,
    json_body: Json<Payload>,
) {
    // ...
}

Here the first parameter String is a body extractor, and the second parameter Json<Payload> is also a body extractor. Axum requires the first parameter to implement FromRequestParts, but String does not - it consumes the body. Even if you swapped the order, you would still have two body extractors, which violates the "only one body-consuming extractor" rule.

The mental model to hold onto: FromRequestParts extractors work on the request head, which is cheap and reusable. FromRequest extractors consume the body, which is a one-shot stream. Axum's type system is the guardrail that prevents you from accidentally consuming the body twice or reading it before the metadata extractors have done their work.

Building up from a simple starter example

The smallest useful example with multiple extractors is a handler that takes a Path and a Query. Neither consumes the body, so both are FromRequestParts extractors. The order between them matters for execution but not for trait satisfaction - both satisfy the same trait bound.

use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Filters {
    sort: Option<String>,
    limit: Option<u32>,
}
async fn list_products(
    Path(category): Path<String>,
    Query(filters): Query<Filters>,
) -> String {
    let sort_order = filters.sort.unwrap_or_else(|| "name".to_string());
    let limit = filters.limit.unwrap_or(10);
    format!(
        "Listing products in category '{}' sorted by '{}' limited to {} items",
        category, sort_order, limit
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/products/{category}", get(list_products));
    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();
}

A request to GET /products/electronics?sort=price&limit=25 runs Path<String> first and Query<Filters> second. Both read from the request head - the URL - so neither cares about the body. The order is arbitrary from a trait perspective, but Axum still executes them left to right.

Now extend the example with a body-consuming extractor. Add a Json payload that contains a product update, and make the handler a POST:

use axum::{
    extract::{Path, Query},
    Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Filters {
    include_inactive: bool,
}
#[derive(Deserialize)]
struct ProductUpdate {
    name: String,
    price_cents: u64,
}
async fn update_product(
    Path(product_id): Path<u32>,
    Query(filters): Query<Filters>,
    Json(update): Json<ProductUpdate>,
) -> String {
    format!(
        "Updating product {} (include_inactive: {}) with name '{}' at {} cents",
        product_id, filters.include_inactive, update.name, update.price_cents
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/products/{product_id}", post(update_product));
    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();
}

When a client sends POST /products/7?include_inactive=true with a JSON body of {"name":"Desk Lamp","price_cents":3499}, Axum runs Path first, then Query, then Json. The first two are FromRequestParts extractors - they read the URL. The last one is FromRequest - it consumes the body. This signature satisfies Axum's rule: every non-final parameter implements FromRequestParts, and the final parameter implements FromRequest.

Execution order is still left to right:

Even though Json must be last, you should still think of all extractors as running in order. Path completes before Query starts, and Query completes before Json starts. If Path fails, Query and Json never get a chance to run.

Why the body extractor must be last

The rule is not arbitrary. The request body is an asynchronous stream, which means it doesn't arrive all at once - chunks of bytes stream in over the network. An extractor that reads the body has to wait for all the chunks to arrive, buffer them, and then parse them. During that time, the request's head data (method, headers, URI) is fully available and cheap to access. But the body stream itself can only be consumed once.

If Axum allowed a body extractor in any position other than last, the same stream could be handed to two consumers, or a metadata extractor could run after the body was already gone. Rather than checking for those situations at runtime, Axum rules them out in the type system: the Handler implementation requires every parameter except the last to implement FromRequestParts, and only the last parameter may implement FromRequest. A body extractor anywhere else fails to compile, so the bad ordering never reaches a running server.

Consider a handler like this:

use axum::{
    extract::{Path, State},
    http::{Method, HeaderMap},
    Json,
    routing::patch,
    Router,
};
use serde::Deserialize;
#[derive(Clone)]
struct AppConfig {
    max_name_length: usize,
}
#[derive(Deserialize)]
struct RenameRequest {
    new_name: String,
}
async fn rename_file(
    method: Method,
    Path(file_id): Path<u32>,
    headers: HeaderMap,
    State(config): State<AppConfig>,
    Json(body): Json<RenameRequest>,
) -> String {
    let authorization = headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("none");
    format!(
        "{} request to rename file {} with auth '{}' - new name: '{}' (max length: {})",
        method, file_id, authorization, body.new_name, config.max_name_length
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/files/{file_id}/rename", patch(rename_file))
        .with_state(AppConfig {
            max_name_length: 100,
        });
    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();
}

Every parameter except the last reads from the request head or application state. Json is the only body consumer, and it sits at the end. If you reordered Json to be second, third, or fourth, the compiler would emit the same FromRequestParts trait bound error for Json because the earlier parameters would force it to satisfy a trait it cannot.

Handling a common misconception about order and failure

A beginner might assume that because extractors run left to right, the first extractor must be the "most important" one or the one most likely to fail. That is a reasonable intuition, but it doesn't match how Axum works. The order rule is about execution sequence and body consumption - not about ranking extractors by importance.

If you want a specific extractor to run first and reject the request before other extractors run, you do that by placing it first in the parameter list. But you should not read "first" as "most important" in a semantic sense. A handler that reads a Path first will reject invalid path parameters before it ever looks at the query string. That is a consequence of order, not a statement about which extractor matters more.

Here is a concrete illustration. Suppose you want to log the HTTP method before doing anything else. Place Method first:

use axum::{
    extract::{Path, Query},
    http::Method,
    Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
    q: String,
}
#[derive(Deserialize)]
struct NotePayload {
    content: String,
}
async fn add_note(
    method: Method,
    Path(notebook_id): Path<u32>,
    Query(params): Query<SearchParams>,
    Json(note): Json<NotePayload>,
) -> String {
    format!(
        "{} request - notebook {}, query '{}', note content '{}'",
        method, notebook_id, params.q, note.content
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/notebooks/{notebook_id}/notes", post(add_note));
    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();
}

Here Method runs first. If you wanted to reject certain HTTP methods early, placing Method first means the handler never reaches Path or Json for those rejected cases. The order does real work, but you choose it based on what you need to check first, not on a ranking of extractor importance.

What happens when extractors fail

When an extractor fails, Axum stops executing the chain and returns a rejection response to the client. The handler is never called. Because extractors run left to right, the first failing extractor in the chain is the one whose rejection gets returned.

This means the position of an extractor affects which failure a client sees. Consider a handler with a Path<u32> first and a Json<Payload> last. If the path contains a non-numeric value, Path fails with a 400 Bad Request and Json never runs - even if the body was also malformed. If the path is valid but the JSON body has a syntax error, Path succeeds, Json fails, and the client gets the JSON rejection.

Order determines which rejection is returned:

Since extractors execute in parameter order, the first one to fail produces the rejection. A client sending both an invalid path and an invalid body will only ever see the path rejection, because the path extractor runs first and stops the chain. Keep this in mind when designing error responses - the order of your parameters affects what clients experience.

The parts and body split in plain language

Under the hood, Axum splits an incoming request into two pieces: the head and the body. The head contains the method, URI, HTTP version, headers, and extensions. The body contains the streaming bytes. This split is why two different traits exist.

FromRequestParts extractors get a mutable reference to the head (Parts) and access to application state. They cannot touch the body. FromRequest extractors get the entire Request, which includes both the head and the body. They can read anything, but because they own the request, they are the only extractor that can consume the body.

When you write a handler with multiple extractors, Axum's internal machinery repeatedly calls from_request_parts on the head for every non-final parameter. That works because the head is cheaply shareable and doesn't get consumed. Then, for the final parameter, Axum calls from_request on the full request, handing over the body. The split is what allows many metadata extractors to coexist with exactly one body extractor.

This model also explains why you cannot have a String body extractor followed by a Json body extractor. Only the last parameter may implement FromRequest, so a handler with two body extractors fails to compile: the first one would have to implement FromRequestParts, which it cannot, because it consumes the body. There is no safe way to hand the same stream to two consumers, so Axum forbids it at the trait level.

Checking your handler signatures against the rules

Whenever you write a handler with multiple extractors, run through these checks before you build:

  1. Identify which parameters consume the request body.
  2. Count them - there must be zero or one.
  3. If there is one, confirm it is the final parameter.
  4. Confirm every non-final parameter implements FromRequestParts (in practice, this is automatic for the built-in metadata extractors).

If all four checks pass, your handler compiles and runs as expected. If any check fails, move the body-consuming extractor to the end or remove one of the duplicate body consumers.

The compiler is your best check:

You don't need to memorize which extractors consume the body - the compiler tells you when you get it wrong. When you see a trait bound error mentioning FromRequestParts on a type like String, Json, Form, or Bytes, it means that extractor is in the wrong position. Move it to the end and rebuild.

The relationship between parameter order and handler clarity

The order rule is not just a compiler constraint - it also shapes how readable your handler signatures are. A convention has emerged in the Axum community: put application state first, then request metadata, then any path or query parameters, and finally the body. This mirrors the natural flow of a request - state is established early, the URL identifies what the client wants, and the body carries the payload.

Here is an example that follows that convention:

use axum::{
    extract::{Path, Query, State},
    http::{HeaderMap, Method},
    Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Clone)]
struct SharedState {
    api_version: String,
}
#[derive(Deserialize)]
struct Pagination {
    page: u32,
}
#[derive(Deserialize)]
struct CommentPayload {
    text: String,
}
async fn add_comment(
    State(state): State<SharedState>,
    method: Method,
    headers: HeaderMap,
    Path(article_id): Path<u32>,
    Query(pagination): Query<Pagination>,
    Json(comment): Json<CommentPayload>,
) -> String {
    let content_type = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("unknown");
    format!(
        "API {} - {} /articles/{}/comments?page={} - content-type: {} - comment: '{}'",
        state.api_version,
        method,
        article_id,
        pagination.page,
        content_type,
        comment.text
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/articles/{article_id}/comments", post(add_comment))
        .with_state(SharedState {
            api_version: "v2".to_string(),
        });
    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();
}

This signature is long but self-documenting. A reader can see, in order: the shared state, the HTTP method, the headers, the path parameter, the query parameter, and the JSON body. The body sits at the end, which is where the rule requires it. The ordering also happens to be the most readable - state and metadata first, then the URL details, then the payload.

A practical walkthrough of fixing a broken handler

Let's walk through a realistic mistake and its fix. A beginner might write a handler like this, thinking the order doesn't matter:

use axum::{
    extract::Path,
    http::HeaderMap,
    Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Message {
    content: String,
}
// This will not compile.
async fn send_message(
    Json(message): Json<Message>,
    Path(channel_id): Path<u32>,
    headers: HeaderMap,
) -> String {
    format!(
        "Sending '{}' to channel {} with headers {}",
        message.content,
        channel_id,
        headers.len()
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/channels/{channel_id}/messages", post(send_message));
    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();
}

The problem is obvious once you know the rule: Json consumes the body but sits first. The compiler error mentions that Json<Message> does not implement FromRequestParts. The fix is to move Json to the end:

use axum::{
    extract::Path,
    http::HeaderMap,
    Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Message {
    content: String,
}
async fn send_message(
    Path(channel_id): Path<u32>,
    headers: HeaderMap,
    Json(message): Json<Message>,
) -> String {
    format!(
        "Sending '{}' to channel {} with headers {}",
        message.content,
        channel_id,
        headers.len()
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/channels/{channel_id}/messages", post(send_message));
    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();
}

Now Path and HeaderMap - both FromRequestParts extractors - come first, and Json sits last. The handler compiles. A request to POST /channels/5/messages with a JSON body of {"content":"Hello"} runs Path first, then HeaderMap, then Json, and the handler formats the response.

Fixed handler compiles and runs:

After the reorder, this handler works as intended. The body extractor is last, the metadata extractors are first, and the response body contains the expected text.

When a handler takes no body extractor at all

Not every handler needs to read the body. If all your extractors are FromRequestParts extractors, the rule about body extractors being last doesn't constrain you at all. The left-to-right execution order still applies, but every parameter satisfies the same trait bound.

Here is a handler that only reads from the request head:

use axum::{
    extract::{Path, Query},
    http::{HeaderMap, Method},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct FilterParams {
    active_only: Option<bool>,
}
async fn list_users(
    method: Method,
    Path(team_id): Path<String>,
    Query(filters): Query<FilterParams>,
    headers: HeaderMap,
) -> String {
    let active_only = filters.active_only.unwrap_or(false);
    let user_agent = headers
        .get("user-agent")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("unknown");
    format!(
        "{} /teams/{}/users?active_only={} - user-agent: {}",
        method, team_id, active_only, user_agent
    )
}
#[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();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

All four extractors - Method, Path, Query, and HeaderMap - implement FromRequestParts. None consumes the body. Axum still runs them in order: Method first, then Path, then Query, then HeaderMap. The body is never read, which is fine because the client is making a GET request that typically has no body.

Thinking about extractor order like a pipeline

A useful mental model is to picture each extractor as a station on an assembly line. The request enters at the left. Each station examines the request, picks out the piece it needs, and passes the request along. Some stations only look at the label on the outside (the request head). One station, at the very end, opens the box and takes the content (the body). Because the box can only be opened once, there is exactly one station allowed to do that, and it must be the last one so nothing after it tries to use the now-empty box.

This pipeline view explains both rules at once. Left-to-right order means each station runs in sequence. Body-last means the station that opens the box sits at the end so no later station depends on the box's contents. If you keep this picture in mind, handler signatures become almost self-explanatory.

Summary

The single most important takeaway is that body-consuming extractors must be last. That rule is enforced at compile time through the FromRequestParts and FromRequest trait split. The left-to-right execution rule then tells you what happens when a request arrives: extractors run in the order they appear in your parameter list, and the first one to fail stops the chain and produces a rejection.

These rules together mean you should structure handler signatures with state and metadata first, URL parameters next, and the body payload last. When you get a compile error about FromRequestParts, look for a body extractor in the wrong position and move it to the end. Once the rule clicks, writing handlers with multiple extractors becomes a matter of arranging parameters to match the natural flow of a request.