Custom FromRequestParts Implementation in Axum

Learn how to build a custom Axum extractor that reads request metadata without touching the body, using FromRequestParts with many beginner-friendly examples.

When you build an Axum application, you often need to pull information out of an incoming request before your handler runs. Axum's built‑in extractors like Path, Query, and HeaderMap already cover many cases, but sometimes your application has a very specific piece of data to collect - a particular header, a value from application state, or something derived from the request metadata. That is where a custom extractor comes in.

This page focuses on implementing FromRequestParts, the trait you use when your extractor does not need to read the request body. You only need access to the request's parts - things like headers, method, URI, and extensions. If you ever need the raw body, you'd implement FromRequest instead, but that's a different page.

What are request parts?:

In Axum, a request is split into two pieces: the parts (metadata like method, headers, URI) and the body (the actual data being sent). FromRequestParts gives you only the parts, which means your extractor runs fast and never consumes the body. That keeps the body available for later extractors in the same handler.

Understanding the Trait Signature

Before writing a custom extractor, you need to recognize the shape of the FromRequestParts trait. Its full definition looks like this:

use axum::{
    extract::FromRequestParts,
    http::request::Parts,
};
// Simplified version
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;
}

Don't be intimidated - the key ideas are:

  • S is your application state type (or () if you have no state). Your implementation works for any state that is Send + Sync.
  • Parts gives you access to headers, method, uri, extensions, etc.
  • Self::Rejection is the error type you return when extraction fails. It must be something Axum can turn into an HTTP response.
  • The method is async in practice; you can write async fn directly in the impl block.

The Smallest Possible Custom Extractor

Let's create an extractor that does almost nothing: it simply returns the request method as a string. This shows the minimal structure.

use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    http::Method,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
// The extractor type
struct RequestMethod(pub Method);
impl<S> FromRequestParts<S> for RequestMethod
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;
    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        Ok(RequestMethod(parts.method.clone()))
    }
}
async fn handler(RequestMethod(method): RequestMethod) -> String {
    format!("You used the {} method", method)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

In this code:

  • We define a struct RequestMethod that holds a Method. The inner value is public (pub) so the handler can destructure it.
  • The impl<S> FromRequestParts<S> for RequestMethod block works for any state type S that is Send + Sync.
  • Rejection = Infallible means this extractor can never fail - we always return Ok.
  • The from_request_parts method receives &mut Parts and a shared reference to the state (_state because we ignore it). We clone the HTTP method out of the parts and store it.
  • In the handler, we use pattern matching: RequestMethod(method) extracts the Method back out. Because the field is pub, the destructuring works from outside the module.

This extractor runs before the handler is called. If you send a GET request to /, you'll see You used the GET method.

Why this is useful:

Even though this exact extractor is trivial, it demonstrates the complete skeleton. Every custom FromRequestParts implementation you write will follow these same steps: define a type, implement the trait, specify a rejection, and write the async function that fills the type from Parts.

Extracting a Header - A Realistic Example

The official Axum documentation uses a User-Agent extractor as its example. Let's expand that into a complete, runnable program with more explanation.

The goal: create an extractor that reads the User-Agent header from the request. If the header is missing, return a 400 Bad Request error. If it exists, wrap the value in our own type.

use axum::{
    extract::FromRequestParts,
    http::header::USER_AGENT,
    http::request::Parts,
    http::{HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
// Our custom extractor: a wrapper around HeaderValue
struct ExtractUserAgent(pub HeaderValue);
impl<S> FromRequestParts<S> for ExtractUserAgent
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        if let Some(user_agent) = parts.headers.get(USER_AGENT) {
            Ok(ExtractUserAgent(user_agent.clone()))
        } else {
            Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing"))
        }
    }
}
async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) -> String {
    format!("Your user agent is: {}", user_agent.to_str().unwrap_or("unknown"))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here's what's new:

  • We import USER_AGENT constant and HeaderValue from axum::http.
  • The rejection type is (StatusCode, &'static str). Axum knows how to turn that tuple into an HTTP response: the status code plus a plain text message. This is a common pattern for quick custom errors.
  • Inside from_request_parts, we look up the header with parts.headers.get(USER_AGENT). This returns an Option<&HeaderValue>. If present, we clone it (because HeaderValue is cheap to clone) and wrap it. If missing, we return an error tuple.
  • The handler extracts the inner HeaderValue and tries to convert it to a string with to_str(), falling back to "unknown" for non‑UTF‑8 values.

Run the server and send a request with curl:

curl http://127.0.0.1:3000/

You'll get:

Your user agent is: curl/8.5.0

If you omit the header (for example with curl -H "User-Agent:"), you'll receive a 400 Bad Request with the message. Note that the header is optional, so real clients do sometimes omit it.

Do not forget to clone:

parts.headers.get() returns a reference that lives only as long as the Parts argument. You cannot store that reference in your extractor because the extractor will outlive the method call. Always clone the HeaderValue (or any other owned data) before returning.

Custom Rejection Types for Clearer Errors

Using (StatusCode, &'static str) works, but it's limited to a fixed message. Often you want to include dynamic information, or make the rejection type part of your public API. You can define a custom error enum that implements IntoResponse.

Let's rewrite the user‑agent extractor to use a custom rejection:

use axum::{
    extract::FromRequestParts,
    http::header::USER_AGENT,
    http::request::Parts,
    http::{HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
#[derive(Debug)]
enum UserAgentError {
    Missing,
    InvalidUtf8,
}
impl IntoResponse for UserAgentError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            UserAgentError::Missing => (StatusCode::BAD_REQUEST, "User-Agent header is required"),
            UserAgentError::InvalidUtf8 => (StatusCode::BAD_REQUEST, "User-Agent contained invalid characters"),
        };
        (status, message).into_response()
    }
}
struct ExtractUserAgent(pub String);
impl<S> FromRequestParts<S> for ExtractUserAgent
where
    S: Send + Sync,
{
    type Rejection = UserAgentError;
    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        let header = parts.headers.get(USER_AGENT).ok_or(UserAgentError::Missing)?;
        let value = header.to_str().map_err(|_| UserAgentError::InvalidUtf8)?;
        Ok(ExtractUserAgent(value.to_owned()))
    }
}
async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) -> String {
    format!("Hello, your user agent is {}", user_agent)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This version:

  • Defines UserAgentError with two variants: Missing and InvalidUtf8.
  • Implements IntoResponse for the error so it can become an HTTP response. Here we map each variant to a status code and message.
  • The extractor now returns a String instead of HeaderValue, because we convert the header value to a string and own it.
  • We use ? to propagate errors concisely.

This approach gives you complete control over error responses. You could return JSON, set headers, or log inside into_response. It also makes the extractor easier to reuse in different handlers because the rejection type is descriptive.

Rejection types must be IntoResponse:

Every extractor's Rejection type must implement IntoResponse. If you forget to implement it, the compiler will complain when Axum tries to turn your rejection into an HTTP response. The error message often points to the handler signature, but the root cause is the missing implementation.

Using Application State in Your Extractor

Many extractors need access to shared application state - configuration, a database pool, or a client. The state parameter of from_request_parts gives you that access. Let's create an extractor that reads a rate‑limit value from state and adds it as a header to the request for later use.

First, define a state type:

#[derive(Clone)]
struct AppState {
    rate_limit_per_minute: u32,
}

Now the extractor reads that value from state and stores it:

use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
#[derive(Clone)]
struct AppState {
    rate_limit_per_minute: u32,
}
struct RateLimit(pub u32);
impl<S> FromRequestParts<S> for RateLimit
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(
        _parts: &mut Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        Ok(RateLimit(state.rate_limit_per_minute))
    }
}
async fn handler(RateLimit(limit): RateLimit) -> String {
    format!("Your rate limit is {} requests per minute", limit)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        rate_limit_per_minute: 60,
    };
    let app = Router::new()
        .route("/", get(handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This does not compile. The compiler reports error[E0609]: no field 'rate_limit_per_minute' on type '&S'. The state parameter is &S where S is generic, so the compiler has no promise that S is AppState or that it has that field. The correct way is to constrain the implementation to work only for AppState:

use axum::{
    extract::{FromRequestParts, State},
    http::request::Parts,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    rate_limit_per_minute: u32,
}
struct RateLimit(pub u32);
// Implement for S = AppState only
impl FromRequestParts<AppState> for RateLimit {
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(
        _parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        Ok(RateLimit(state.rate_limit_per_minute))
    }
}
async fn handler(RateLimit(limit): RateLimit) -> String {
    format!("Your rate limit is {} requests per minute", limit)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        rate_limit_per_minute: 60,
    };
    let app = Router::new()
        .route("/", get(handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here we changed the generic parameter from S to AppState. That means this extractor can only be used when the application state is exactly AppState. The from_request_parts method now receives &AppState directly, and we can read its fields.

But what if you want the extractor to work with any state that contains the rate limit? You can require the state to implement an interface:

use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
trait HasRateLimit {
    fn rate_limit_per_minute(&self) -> u32;
}
#[derive(Clone)]
struct AppState {
    rate_limit_per_minute: u32,
}
impl HasRateLimit for AppState {
    fn rate_limit_per_minute(&self) -> u32 {
        self.rate_limit_per_minute
    }
}
struct RateLimit(pub u32);
impl<S> FromRequestParts<S> for RateLimit
where
    S: HasRateLimit + Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(
        _parts: &mut Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        Ok(RateLimit(state.rate_limit_per_minute()))
    }
}
async fn handler(RateLimit(limit): RateLimit) -> String {
    format!("Your rate limit is {} requests per minute", limit)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        rate_limit_per_minute: 60,
    };
    let app = Router::new()
        .route("/", get(handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now the extractor is generic over any state that implements HasRateLimit. This is a flexible pattern; you can even use it with Arc<AppState> if you implement the trait for Arc<AppState> as well. A request to / returns Your rate limit is 60 requests per minute.

Trying to use a generic state as a concrete type:

If you write impl<S> FromRequestParts<S> and then try to treat state as &AppState, the code will not compile. Rust cannot know that S is AppState unless you constrain the generic. Always either restrict the implementation to a concrete state type or add a trait bound that gives you access to what you need.

Combining Multiple Header Values and Validating

Sometimes you need to read several pieces of metadata and ensure they are consistent. For example, an extractor that checks for a custom API key header and ensures it is not empty:

use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    http::{HeaderMap, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
#[derive(Debug)]
struct ApiKey(pub String);
#[derive(Debug)]
enum ApiKeyError {
    Missing,
    Empty,
}
impl IntoResponse for ApiKeyError {
    fn into_response(self) -> Response {
        let message = match self {
            ApiKeyError::Missing => "Missing X-API-Key header",
            ApiKeyError::Empty => "X-API-Key header cannot be empty",
        };
        (StatusCode::UNAUTHORIZED, message).into_response()
    }
}
impl<S> FromRequestParts<S> for ApiKey
where
    S: Send + Sync,
{
    type Rejection = ApiKeyError;
    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        const API_KEY_HEADER: &str = "x-api-key";
        let value = parts
            .headers
            .get(API_KEY_HEADER)
            .ok_or(ApiKeyError::Missing)?;
        let key = value.to_str().map_err(|_| ApiKeyError::Empty)?;
        if key.trim().is_empty() {
            return Err(ApiKeyError::Empty);
        }
        Ok(ApiKey(key.to_owned()))
    }
}
async fn handler(ApiKey(key): ApiKey) -> String {
    format!("Authenticated with key: {}", key)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

In this extractor:

  • We use a custom header name x-api-key. Header names in HTTP are case‑insensitive, so HeaderMap::get will find it regardless of case.
  • We check both presence and non‑emptiness (after trimming whitespace).
  • The rejection type has two variants, each mapped to 401 Unauthorized.
  • The handler receives the API key as a String.

You can test it with curl:

curl -H "x-api-key: secret123" http://127.0.0.1:3000/

Returns Authenticated with key: secret123. If you omit the header or send an empty one, you get a 401 with an appropriate message.

Making the Extractor Usable with Result in Handlers

By default, if your extractor returns an error, Axum will send the rejection response and the handler will not run. But sometimes you want to handle the failure inside the handler itself. You can wrap the extractor in Result in the handler signature. Using the ApiKey extractor from the previous section, change only the handler and the route in the same program:

async fn handler(result: Result<ApiKey, ApiKeyError>) -> Response {
    match result {
        Ok(ApiKey(key)) => format!("Valid key: {}", key).into_response(),
        Err(err) => err.into_response(),
    }
}

And register it with .route("/", get(handler)) as before. This gives the same external behavior but lets you inspect the error and possibly return a different response. This is a common pattern when you need more control.

The error type must be public or accessible:

If you plan to use Result<YourExtractor, YourRejection> in a handler signature, the rejection type must be visible to the code that writes the handler. If it's private to a module, the handler cannot name it. Keep rejection types public or re‑export them.

Writing a Unit Test for Your Custom Extractor

Testing custom extractors is straightforward because you can construct a Parts object directly and call from_request_parts. Here's an example using the ApiKey extractor:

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::{HeaderMap, HeaderValue, Method, Uri, Version};
    use axum::extract::FromRequestParts;
    fn make_parts() -> Parts {
        // Parts::new() is private, so build Parts by splitting a real request.
        // The default request already has method GET, uri "/", HTTP/1.1, and empty headers.
        axum::http::Request::new(axum::body::Body::empty())
            .into_parts()
            .0
    }
    #[tokio::test]
    async fn missing_api_key_rejected() {
        let mut parts = make_parts();
        let result = ApiKey::from_request_parts(&mut parts, &())
            .await
            .unwrap_err();
        assert!(matches!(result, ApiKeyError::Missing));
    }
    #[tokio::test]
    async fn valid_api_key_accepted() {
        let mut parts = make_parts();
        parts.headers.insert(
            "x-api-key",
            HeaderValue::from_static("secret"),
        );
        let ApiKey(key) = ApiKey::from_request_parts(&mut parts, &())
            .await
            .unwrap();
        assert_eq!(key, "secret");
    }
}

In this test, we manually construct Parts and set headers. We call the extractor function directly with &() as the state (unit state). This pattern works because FromRequestParts is an async function that does not require a full request. Add this test module at the bottom of the same src/main.rs that holds the ApiKey extractor. The #[tokio::test] attribute needs tokio's macros and rt-multi-thread features, so add them to the tokio line in Cargo.toml: tokio = { version = "1", features = ["full"] } already includes them.

Testing extractors is simple:

Because from_request_parts only needs &mut Parts and &S, you can test it in isolation without spinning up a server. Just build the Parts struct, set the fields you care about, and call the method. This keeps tests fast and focused.

Common Mistakes When Implementing FromRequestParts

Here are several pitfalls beginners often hit, along with how to avoid them.

Forgetting the Send + Sync bounds on the state

Axum runs handlers on a multithreaded runtime, so the state type must be Send + Sync (a state holding a raw pointer or a non-thread-safe cell would not qualify). Your extractor needs to work with whatever state the application uses, so include the where S: Send + Sync clause on the implementation. If you forget it, the compiler may complain that S is not Send or Sync when the handler is registered. Always include that bound unless you have a good reason.

Trying to return a reference from Parts

from_request_parts returns an owned Self. You cannot store a reference to data inside Parts because Parts is borrowed only for the duration of the call. If you need to keep a header value or other data, clone it into an owned type (like HeaderValue, String, or Vec<u8>).

Assuming the extractor can consume the body

FromRequestParts never sees the request body. If you need to read the body, you must implement FromRequest instead. Attempting to access body inside FromRequestParts will fail because the method doesn't receive it.

Not implementing IntoResponse for the rejection type

Every rejection must be convertible into an HTTP response. If you define a custom error type but forget impl IntoResponse, the compiler will show an error in the handler signature (often about the handler not being a valid handler). Always check that your rejection type implements IntoResponse.

Using a generic state but trying to access concrete fields

As shown earlier, if you write impl<S> FromRequestParts<S> and then treat state as if it were your AppState, you'll get a compile error. Either restrict the implementation to a concrete state type or add a trait bound that exposes the fields you need.

Overcomplicating the rejection type

For simple extractors used in one place, (StatusCode, &'static str) is often enough. Don't create a complex enum unless you need to distinguish between multiple failure modes or the extractor is part of a library. Simplicity aids readability.

Accessing request extensions incorrectly:

Parts includes an extensions map (parts.extensions) which can hold arbitrary data inserted by middleware. If your extractor reads from it, remember that the type you insert must match the type you retrieve. A common mistake is inserting a value of type String and then trying to get it as &str, or vice‑versa. Always use parts.extensions.get::<YourType>() with the exact type.

When to Use FromRequestParts vs FromRequest

The decision is simple:

  • FromRequestParts - when you only need request metadata (method, URI, headers, extensions) and never need the body. It is cheaper and allows other extractors after it to also use the body.
  • FromRequest - when you need to read or consume the request body (e.g., JSON, form data, raw bytes). Because the body can only be read once, Axum requires that only the last extractor in a handler be FromRequest, and all others must be FromRequestParts.

This page covers only FromRequestParts. If you find yourself needing the body, you'll need to implement FromRequest instead. But that's a separate topic.

Building a Reusable Library‑Style Extractor

When you create an extractor that will be used across multiple projects or by other developers, you should think about its public API. Here's an example of a well‑designed extractor that reads a custom X-Request-ID header and falls back to generating a UUID if missing.

use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    http::{HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use uuid::Uuid; // add `uuid = { version = "1", features = ["v4"] }` to Cargo.toml
pub struct RequestId(pub String);
impl<S> FromRequestParts<S> for RequestId
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;
    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        const HEADER: &str = "x-request-id";
        if let Some(value) = parts.headers.get(HEADER) {
            if let Ok(s) = value.to_str() {
                return Ok(RequestId(s.to_owned()));
            }
        }
        // Generate a new UUID if header is missing or invalid
        Ok(RequestId(Uuid::new_v4().to_string()))
    }
}
async fn handler(RequestId(id): RequestId) -> String {
    format!("Request ID: {}", id)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This extractor never fails (Infallible rejection). It tries to read the X-Request-ID header; if it's present and valid UTF‑8, it uses that value. Otherwise it generates a new UUID. This pattern is useful for request tracking in logs - you can later use the request ID in middleware or handlers to correlate logs.

Because the rejection is Infallible, you don't need to implement IntoResponse (it's already implemented for Infallible). This is a nice property: if your extractor can't fail, you avoid writing error handling code.

Summary

Implementing FromRequestParts gives you a clean way to encapsulate request‑metadata extraction logic. You define a struct that holds the extracted data, implement the trait with a rejection type, and write one async function. That function receives the request parts and application state, and returns either your struct or an error.

The key points to remember:

  • FromRequestParts is for metadata only - no body access.
  • Your extractor must be generic over S with S: Send + Sync, or restricted to a concrete state type.
  • The rejection type must implement IntoResponse.
  • Always clone any data you want to keep from Parts.
  • You can test extractors in isolation by constructing Parts manually.
  • Common pitfalls include forgetting the Send + Sync bounds, trying to return references, and accessing the wrong type from extensions.

With this foundation, you can build reusable, well‑tested extractors that keep your handler functions clean and focused. The next logical step is learning how to implement FromRequest for body‑consuming extractors, which builds on the same principles but adds the complexity of handling the request body.