FromRequestParts in handlers

Learn what FromRequestParts is in Axum, when to implement it for custom extractors, and how it differs from FromRequest so you can reuse request metadata cleanly across handlers.

A handler in Axum accepts extractors as arguments. Those extractors all implement one of two traits. On this page we focus on the first of those two: FromRequestParts. This trait is the foundation for most custom extractors you will write, and understanding it makes the difference between copying boilerplate into every handler and creating one clean, reusable piece of code.

What FromRequestParts Actually Is

FromRequestParts is a trait. In Rust, a trait is a contract that says: "anything implementing this trait is guaranteed to provide certain methods." For FromRequestParts, that method allows Axum to build a value from the parts of an incoming HTTP request.

"Parts" is a precise term here. Axum splits every request into two logical halves. The first half is the metadata: headers, method, URI, HTTP version, extensions, and application state. The second half is the body: the raw bytes the client sends after the headers, such as JSON, form data, or file content.

FromRequestParts only has access to the first half. It cannot read the request body. If you need the body, you need the sibling trait called FromRequest, which receives the body and whose details belong on its own page. The distinction matters because it affects what your custom extractor can do.

Why the split exists:

Axum separates request metadata from the request body so extractors that only need headers, state, or method can run without consuming the body. Once you read a request body in Rust, you generally cannot read it again. By keeping metadata-only extractors separate, Axum leaves the body untouched for other extractors or middleware that may run later.

Why FromRequestParts Exists

Handlers often need the same small piece of information over and over. A user ID from a header. The request method. A client identifier parsed from a query parameter. Without extractors, every handler would start with the same five or six lines of manual parsing, error checking, and option handling.

FromRequestParts exists so you can encapsulate that parsing once. You create a struct, implement the trait for it, and after that you can drop the struct directly into any handler signature. Axum calls your implementation automatically before the handler body runs.

This solves three concrete problems. It removes duplicated parsing logic from handlers. It gives parsing failures a consistent error path through Axum's rejection system. It makes handler signatures self-documenting because the extractor name tells you exactly what the handler depends on.

You already use this every day:

Every built-in extractor such as HeaderMap, Query, Path, State, and Extension implements FromRequestParts. If you have used any of these in a handler, you have already relied on this trait. The only step left is learning to implement it yourself.

The Trait in Plain Language

The FromRequestParts trait requires two things from your type:

  • An associated type named Rejection, which describes the error that can occur during extraction.
  • A method named from_request_parts that receives the request parts and application state and returns either your type or that rejection.

The method signature in the Axum source looks roughly like this:

pub trait FromRequestParts<S>: Sized {
    type Rejection: IntoResponse;
    fn from_request_parts(
        parts: &mut Parts,
        state: &S,
    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
}

Do not worry if every symbol here is not familiar yet. The important ideas are that extraction is asynchronous, it can fail, and when it fails it returns an error type you define that Axum knows how to turn into an HTTP response.

The Parts type is a struct Axum uses to hold the method, headers, URI, extensions, and version of the request. The S is your application state type, which may be () if your app does not use state. We will keep state out of the first examples and add it later.

How a Built-In Extractor Uses This

Before writing a custom implementation, it helps to see a built-in extractor working at the handler level. The HeaderMap extractor gives you every request header in one value. It implements FromRequestParts. You do not call its method yourself; Axum does.

Here is a complete runnable application:

// Cargo.toml
// [dependencies]
// axum = "0.8"
// tokio = { version = "1", features = ["full"] }
use axum::{
    http::HeaderMap,
    routing::get,
    Router,
};
async fn show_headers(headers: HeaderMap) -> String {
    match headers.get("user-agent") {
        Some(value) => format!("Your user agent is: {}", value.to_str().unwrap_or("unprintable")),
        None => "You did not send a user-agent header.".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/headers", get(show_headers));
    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 arrives at /headers, Axum sees the headers: HeaderMap argument in show_headers. It knows HeaderMap implements FromRequestParts, so it calls the trait method, obtains the result, and only then invokes your handler function. Inside the handler, headers is already a populated value. The handler does not perform extraction; it receives the outcome of extraction.

If you run this and visit http://127.0.0.1:3000/headers in a browser, the browser will send a user-agent header automatically, so you should see output similar to:

Your user agent is: Mozilla/5.0 ...

Writing Your First Custom FromRequestParts Extractor

A realistic first custom extractor is one that reads a single header and converts it into a typed value. Suppose your application requires clients to send an x-api-key header with every request to protected routes. Instead of checking that header inside each handler, you create an extractor called ApiKey.

First, define the struct that will hold the parsed value, then implement FromRequestParts for it. The implementation will look for the header, reject if it is missing, and reject if the value cannot be converted to a string.

use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
};
pub struct ApiKey(pub String);
pub struct MissingApiKey;
impl IntoResponse for MissingApiKey {
    fn into_response(self) -> Response {
        (
            StatusCode::UNAUTHORIZED,
            "Missing x-api-key header. Please include a valid API key.",
        )
            .into_response()
    }
}
impl<S> FromRequestParts<S> for ApiKey
where
    S: Send + Sync,
{
    type Rejection = MissingApiKey;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let headers = &parts.headers;
        let value = headers
            .get("x-api-key")
            .ok_or(MissingApiKey)?
            .to_str()
            .map_err(|_| MissingApiKey)?;
        Ok(ApiKey(value.to_string()))
    }
}

The struct has one public field containing the key string. The field is public so handlers can access the value after extraction succeeds.

Let us walk through this implementation slowly because it is the core pattern for nearly every custom extractor you will ever write.

The impl<S> FromRequestParts<S> for ApiKey block works for any application state type S that is Send and Sync. You do not need to know the exact meaning of those traits yet. The where S: Send + Sync bound is required by Axum because extractors run inside concurrent server tasks, and the compiler must be able to prove the state is safe to share.

The associated type Rejection is set to MissingApiKey. This means every failure path in from_request_parts returns that type. The MissingApiKey type implements IntoResponse, which is why it can describe an HTTP 401 response when extraction fails. The rejection is your custom error type, and Axum will call its into_response method automatically if extraction fails.

Inside the method, parts.headers gives you a reference to the request headers. The expression headers.get("x-api-key") returns an Option<&HeaderValue>. If the header is absent, ok_or(MissingApiKey)? converts the None into an early return of Err(MissingApiKey). If the header is present but contains non-ASCII bytes, to_str() fails and the map_err converts that into the same rejection. Finally, a successful parse is wrapped into an ApiKey value.

The async fn is significant. Even though this implementation does no asynchronous work internally, the trait requires an async method because Axum must be able to run extractors concurrently. You may not have an .await inside the method, and that is fine; an async function without an await simply returns a ready future.

Using the ApiKey Extractor in a Handler

Now that the extractor exists, any handler can request it. Here is the whole program in one file, with the struct, the rejection type, and the implementation included, so you can run it as it stands:

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
pub struct ApiKey(pub String);
pub struct MissingApiKey;
impl IntoResponse for MissingApiKey {
    fn into_response(self) -> Response {
        (
            StatusCode::UNAUTHORIZED,
            "Missing x-api-key header. Please include a valid API key.",
        )
            .into_response()
    }
}
impl<S> FromRequestParts<S> for ApiKey
where
    S: Send + Sync,
{
    type Rejection = MissingApiKey;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let headers = &parts.headers;
        let value = headers
            .get("x-api-key")
            .ok_or(MissingApiKey)?
            .to_str()
            .map_err(|_| MissingApiKey)?;
        Ok(ApiKey(value.to_string()))
    }
}
async fn protected_handler(api_key: ApiKey) -> String {
    format!("Access granted with API key: {}", api_key.0)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/protected", get(protected_handler));
    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();
}

With axum = "0.8" and tokio = { version = "1", features = ["full"] } in Cargo.toml, run it and test both cases:

curl http://127.0.0.1:3000/protected
# Response: 401 Unauthorized, body "Missing x-api-key header. Please include a valid API key."
curl -H "x-api-key: secret123" http://127.0.0.1:3000/protected
# Response: Access granted with API key: secret123

When a request arrives at /protected without the x-api-key header, Axum calls from_request_parts, receives Err(MissingApiKey), and immediately returns the 401 response. The handler function never runs. When the header is present, extraction succeeds, ApiKey is passed in, and the handler formats its value.

Extraction failure short-circuits the handler:

If any extractor in a handler's argument list rejects, Axum returns that rejection immediately and never calls the handler body. This is intentional and useful. It means you can rely on your extractors to validate preconditions before any business logic runs.

Returning Rejection Types from from_request_parts

One common source of confusion is what happens when your from_request_parts returns a rejection. The rejection flows into Axum's response system and becomes the HTTP response sent to the client. In the previous example, MissingApiKey implements IntoResponse, so it directly describes that 401 status and message.

But the rejection can be simpler. You can return StatusCode itself as the rejection type, since StatusCode implements IntoResponse. Here is a minimal extractor that returns 401 directly:

use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
};
pub struct RequireAuth;
impl<S> FromRequestParts<S> for RequireAuth
where
    S: Send + Sync,
{
    type Rejection = StatusCode;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        if parts.headers.contains_key("x-auth-token") {
            Ok(RequireAuth)
        } else {
            Err(StatusCode::UNAUTHORIZED)
        }
    }
}

RequireAuth is a unit struct, meaning it has no fields. Handlers use it purely as a gate: if the header exists, the handler runs; if not, Axum returns 401 with an empty body. This pattern is common for simple authorization checks where you do not need to pass any value into the handler, only to block unauthorized requests.

A handler using RequireAuth looks like this:

async fn dashboard(_auth: RequireAuth) -> &'static str {
    "Welcome to your dashboard."
}

You should name the argument _auth or _ if you do not use its value inside the handler - otherwise Rust only warns about the unused variable (it still compiles), and the underscore prefix silences that warning. The extractor's entire job in this case is gatekeeping, not providing data.

Extracting Data from Path and Query

FromRequestParts has access to the request URI, which includes both the path and the query string. You can parse custom values from either. Axum provides built-in Path and Query extractors for typed access, and those already implement FromRequestParts. But seeing how to access the raw URI in your own implementation clarifies what the trait can touch.

Consider an extractor that reads a tenant query parameter and exposes it as a string:

use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
};
pub struct Tenant(pub String);
pub struct MissingTenant;
impl IntoResponse for MissingTenant {
    fn into_response(self) -> Response {
        (
            StatusCode::BAD_REQUEST,
            "Missing tenant query parameter. Use /path?tenant=example",
        )
            .into_response()
    }
}
impl<S> FromRequestParts<S> for Tenant
where
    S: Send + Sync,
{
    type Rejection = MissingTenant;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let query = parts.uri.query().ok_or(MissingTenant)?;
        let mut tenant_value = None;
        for pair in query.split('&') {
            if let Some((key, value)) = pair.split_once('=') {
                if key == "tenant" {
                    tenant_value = Some(value.to_string());
                }
            }
        }
        tenant_value.map(Tenant).ok_or(MissingTenant)
    }
}

This implementation manually parses the query string. In a real application you would probably use the built-in Query extractor with a typed struct instead of parsing by hand. The manual version is educational: it shows that the raw query string is available through parts.uri.query() and that you can parse it however you need.

A handler using this extractor:

async fn show_tenant(tenant: Tenant) -> String {
    format!("You belong to tenant: {}", tenant.0)
}

The URL http://127.0.0.1:3000/tenant?tenant=acme would produce:

You belong to tenant: acme

The URL without the query parameter returns a 400 response with the rejection body.

Multiple Extractors in One Handler

FromRequestParts extractors can be stacked. A handler may accept several of them, and Axum runs all extractions before invoking the handler. If any one fails, the whole request fails with that extractor's rejection.

async fn tenant_report(
    _auth: RequireAuth,
    tenant: Tenant,
    api_key: ApiKey,
) -> String {
    format!("Report for tenant {} using key {}", tenant.0, api_key.0)
}

All three extractors run independently. The handler only runs if RequireAuth, Tenant, and ApiKey all extract successfully. This composition gives you a declarative way to express preconditions: a handler that requires auth, a tenant, and an API key simply states those requirements in its signature.

Extractor order does not change the result here:

For these three FromRequestParts implementations, the argument order in the handler signature does not change what each extractor sees - each one reads the same immutable parts. Axum does run them in order, left to right, and returns the first rejection it encounters in that order.

Implementing FromRequestParts Using State

Everything so far used a phantom state type S and ignored it. The from_request_parts method also receives &S, which is your application's shared state. You can use that state during extraction.

Suppose you store a configured API key in application state and want the extractor to validate the incoming header against that configured value rather than merely checking that a header exists.

First, define the state struct:

#[derive(Clone)]
pub struct AppState {
    pub expected_api_key: String,
}

Then implement the extractor with S = AppState in mind. You can make the implementation generic over S and only call methods available on S, or you can implement directly for AppState. The direct implementation is simpler when the extractor is specific to one application.

use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
#[derive(Clone)]
pub struct AppState {
    pub expected_api_key: String,
}
pub struct ValidatedApiKey;
pub struct InvalidApiKey;
impl IntoResponse for InvalidApiKey {
    fn into_response(self) -> Response {
        (StatusCode::UNAUTHORIZED, "Invalid or missing API key.").into_response()
    }
}
impl FromRequestParts<AppState> for ValidatedApiKey {
    type Rejection = InvalidApiKey;
    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let headers = &parts.headers;
        let provided = headers
            .get("x-api-key")
            .and_then(|value| value.to_str().ok())
            .ok_or(InvalidApiKey)?;
        if provided == state.expected_api_key {
            Ok(ValidatedApiKey)
        } else {
            Err(InvalidApiKey)
        }
    }
}
async fn protected(ValidatedApiKey: ValidatedApiKey) -> &'static str {
    "You provided the correct API key."
}
#[tokio::main]
async fn main() {
    let state = AppState {
        expected_api_key: "secret-123".to_string(),
    };
    let app = Router::new()
        .route("/protected", get(protected))
        .with_state(state);
    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();
}

Notice the implementation block is now impl FromRequestParts<AppState> for ValidatedApiKey, not generic over S. That is valid because AppState is a concrete type. The from_request_parts method compares the incoming header against state.expected_api_key and rejects if they differ.

The state must be registered on the router with .with_state(state), otherwise Axum will not be able to provide it during extraction and compilation will fail. That registration is how Axum knows what value to pass as the &S argument.

State type mismatch causes compile-time errors, not runtime errors:

If your handler uses an extractor expecting AppState but you never call .with_state with an AppState value, or you call it with a different type, the program will fail to compile. This is a deliberate design choice in Axum. State mismatches are caught before the server ever starts.

Rejections That Need Headers Themselves

So far each rejection has returned a fixed status and message. Sometimes a proper rejection must include an HTTP header. For example, a missing authentication token should return 401 Unauthorized with a WWW-Authenticate header telling the client what scheme to use.

You can achieve that by returning a Response built with explicit headers:

use axum::{
    extract::FromRequestParts,
    http::{header, request::Parts, StatusCode},
    response::{IntoResponse, Response},
};
pub struct BearerToken(pub String);
pub struct BearerRejection;
impl IntoResponse for BearerRejection {
    fn into_response(self) -> Response {
        (
            StatusCode::UNAUTHORIZED,
            [(header::WWW_AUTHENTICATE, "Bearer")],
            "A valid bearer token is required.",
        )
            .into_response()
    }
}
impl<S> FromRequestParts<S> for BearerToken
where
    S: Send + Sync,
{
    type Rejection = BearerRejection;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(header::AUTHORIZATION)
            .ok_or(BearerRejection)?
            .to_str()
            .map_err(|_| BearerRejection)?;
        let token = auth_header
            .strip_prefix("Bearer ")
            .ok_or(BearerRejection)?;
        Ok(BearerToken(token.to_string()))
    }
}

The rejection's into_response now returns a tuple containing a status, an array of header pairs, and a body string. Rust's type system lets this tuple implement IntoResponse, which is why the code compiles. The response sent to the client includes the WWW-Authenticate: Bearer header, which HTTP clients use to decide how to retry the request.

Common Mistakes and Misconceptions

Confusing FromRequestParts with FromRequest

The most frequent mistake is implementing FromRequestParts when the extractor actually needs the request body. If you need JSON, form data, raw bytes, or any body content, FromRequestParts cannot give it to you. You must implement FromRequest instead, which has a different method signature that receives the body.

FromRequestParts only sees &mut Parts. Any attempt to access the body from within it is impossible by design. If you find yourself trying to call something like parts.body, stop and reconsider: you need the other trait.

Panicking Inside from_request_parts

Extraction runs on the server's worker tasks. If you call .unwrap() or .expect() inside from_request_parts and the value is not there, you will panic inside the server task. Depending on the runtime, that panic may terminate the entire request task rather than returning a clean error response.

Always return Err(Self::Rejection) for parse failures instead of panicking. The rejection system exists so that malformed input becomes a normal HTTP error response, not a server crash.

Performing Body-Only Validation in Parts Extractors

A FromRequestParts extractor cannot validate the request body. It can validate headers, method, path, query, and state. If your validation depends on both metadata and body, split it into two extractors: one FromRequestParts for metadata and one FromRequest for the body. Axum will run both before the handler executes.

Forgetting the Send and Sync Bounds

If you make your implementation generic over S but omit where S: Send + Sync, the compiler will complain. That bound is required because Axum runs extraction on worker threads and needs to share the state reference safely. When in doubt, copy the exact trait bounds from the Axum documentation or the examples above.

Silent failures from bad IntoResponse implementations:

If your rejection type implements IntoResponse but that implementation calls .unwrap() on something that may fail, a panic inside into_response drops the connection instead of sending a clean error response, so the client sees the request fail with no useful status or body. Write rejection implementations as total functions that never panic, because they run on the error path, when input is already malformed.

How FromRequestParts Compares to Inline Handler Logic

You can write the API key check directly inside the handler:

async fn protected_inline(headers: HeaderMap) -> Result<String, StatusCode> {
    let api_key = headers
        .get("x-api-key")
        .and_then(|value| value.to_str().ok())
        .ok_or(StatusCode::UNAUTHORIZED)?;
    Ok(format!("Access granted with key: {}", api_key))
}

This works and is perfectly valid for one handler. The extractor approach becomes better when the same check appears in ten handlers. With an extractor, each handler signature is simpler, the check is defined once, and changing the header name or validation rule requires editing one implementation instead of ten handlers.

The extractor also signals intent. A signature like async fn dashboard(api_key: ApiKey) tells a reader immediately that this route is protected by API key validation. The inline version requires reading the handler body to discover the same fact.

Neither approach is wrong. The extractor is a tool for reuse and clarity, not an obligation. Use it when you notice the same FromRequestParts-style parsing appearing in multiple handlers or when the parsing logic is complex enough to deserve its own type.

Simpler Alternatives for Very Small Cases

If the extraction logic is tiny and only needed once, the full struct-and-trait ceremony can feel heavy. Axum offers a lighter alternative: use a built-in extractor like HeaderMap or Query and parse inside the handler. That is the inline example above.

The tradeoff is locality versus reusability. Inline logic is easier for a reader who wants to see everything in one place. A custom extractor is better when you want a named, reusable abstraction with a centralized error type.

There is no performance difference. Both approaches run the same parsing code. The choice is about code organization.

Using Extensions in FromRequestParts

Parts includes an extensions field, a typed map that middleware can populate. If you have middleware that inserts a user ID into extensions, a FromRequestParts extractor can pull it out cleanly.

Suppose middleware inserts a user ID string into extensions. The extractor looks like this:

use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
};
pub struct CurrentUser(pub String);
pub struct UserNotFound;
impl IntoResponse for UserNotFound {
    fn into_response(self) -> Response {
        (StatusCode::UNAUTHORIZED, "Authentication required.").into_response()
    }
}
impl<S> FromRequestParts<S> for CurrentUser
where
    S: Send + Sync,
{
    type Rejection = UserNotFound;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        parts
            .extensions
            .get::<String>()
            .cloned()
            .map(CurrentUser)
            .ok_or(UserNotFound)
    }
}

This depends on some earlier middleware having inserted a String into parts.extensions. If that middleware did not run or the key is missing, the extractor returns 401. This pattern is common for authentication systems where middleware validates a token and the extractor exposes the resulting user identity to handlers without re-validating anything.

Extension types must be unique:

The extensions map uses Rust type identity as the key. If you insert a String and later look up a String, you get the same value. But if you insert a UserId struct and look up a String, they are different entries. Middleware and extractors must agree on the exact Rust type used as the extension key.

A More Complete Real-World Extractor

Here is a larger example that ties together state, headers, extensions, and a meaningful rejection type. It represents an extractor for a request context containing the authenticated user and the client's preferred locale.

use axum::{
    extract::FromRequestParts,
    http::{header, request::Parts, StatusCode},
    response::{IntoResponse, Response},
};
#[derive(Clone)]
pub struct LocaleState {
    pub supported_locales: Vec<String>,
}
pub struct RequestContext {
    pub user_id: String,
    pub locale: String,
}
pub enum ContextRejection {
    MissingUser,
    MissingLocale,
    UnsupportedLocale,
}
impl IntoResponse for ContextRejection {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ContextRejection::MissingUser => (StatusCode::UNAUTHORIZED, "User not authenticated."),
            ContextRejection::MissingLocale => {
                (StatusCode::BAD_REQUEST, "Missing accept-language header.")
            }
            ContextRejection::UnsupportedLocale => (
                StatusCode::NOT_ACCEPTABLE,
                "Requested locale is not supported.",
            ),
        };
        (status, message).into_response()
    }
}
impl FromRequestParts<LocaleState> for RequestContext {
    type Rejection = ContextRejection;
    async fn from_request_parts(
        parts: &mut Parts,
        state: &LocaleState,
    ) -> Result<Self, Self::Rejection> {
        let user_id = parts
            .extensions
            .get::<String>()
            .cloned()
            .ok_or(ContextRejection::MissingUser)?;
        let accept_language = parts
            .headers
            .get(header::ACCEPT_LANGUAGE)
            .and_then(|value| value.to_str().ok())
            .ok_or(ContextRejection::MissingLocale)?;
        let locale = accept_language
            .split(',')
            .next()
            .unwrap_or("")
            .trim()
            .to_string();
        if !state.supported_locales.contains(&locale) {
            return Err(ContextRejection::UnsupportedLocale);
        }
        Ok(RequestContext { user_id, locale })
    }
}

A handler using this extractor receives a fully populated RequestContext:

async fn localized_dashboard(context: RequestContext) -> String {
    format!(
        "Showing dashboard in locale {} for user {}",
        context.locale, context.user_id
    )
}

This extractor does three things: verifies the user is present in extensions, parses the preferred locale from the accept-language header, and checks that the locale is in the state's supported list. Each failure maps to a distinct HTTP status. All of this logic is now reusable across any number of handlers that need the same context.

Comparing to FromRequest Directly

FromRequest extractors receive the entire request, including the body. They are used for things like JSON deserialization, form parsing, and multipart file uploads. FromRequestParts extractors are for metadata and state.

The rule of thumb: if your extractor never touches the body, implement FromRequestParts. If it must read the body, implement FromRequest. The two traits are not interchangeable, and choosing the wrong one leads to a compile-time error because the method signatures differ. A FromRequestParts implementation receives &mut Parts, so there is simply no body to read. A FromRequest implementation receives the whole Request, so it can read the body but must sit last in the handler, after every parts extractor has run.

That ordering is the practical difference you will feel first. A handler can stack as many FromRequestParts extractors as it likes, in any order, because none of them consumes anything. It can have at most one FromRequest extractor, and it goes last. So when you start writing a new extractor, ask what it needs: headers, method, URI, extensions, or state means FromRequestParts; bytes from the body means FromRequest; both means two extractors, one of each kind, composed in the handler signature.

Parts extractors preserve the body for later extractors:

Because a FromRequestParts extractor never consumes the request body, you can combine it with a FromRequest extractor in the same handler. The parts extractor runs first, uses only metadata, and leaves the body untouched for the body extractor to consume afterward.

Summary

FromRequestParts is the trait behind every metadata-based extractor in Axum. It gives your handlers a clean way to receive headers, method, path, query, extensions, and state without duplicating parsing logic. The trait method receives request parts and application state, returns either your custom type or a rejection you define, and runs before the handler body executes.

The key insight is the split between metadata and body. If you catch yourself writing a FromRequestParts implementation that wants the body, stop: you are using the wrong trait. For everything header- or state-related, this trait is the right tool, and mastering its single-method shape unlocks a large portion of clean Axum application design. The decision to write a custom extractor at all follows the same test as anywhere else in this chapter: the second time the same check appears in a handler, give it a name, a type, and a rejection, and let every handler after that declare what it needs in its signature instead of repeating how to get it.