Custom FromRequest implementation in Axum

Learn how to create your own body-consuming extractors by implementing the FromRequest trait in Axum, with many beginner-friendly examples.

When you need to extract data from the body of an incoming HTTP request - and that data is not just plain JSON or a form - you can build your own extractor. In Axum, a body-consuming custom extractor is a type that implements the FromRequest trait. This page walks you through everything you need to write one from scratch, starting with the absolute basics and moving to advanced patterns.

What is FromRequest?

In Axum, any type that can be extracted from an HTTP request is called an extractor. There are two traits that make this possible:

  • FromRequestParts - used when your extractor only needs access to the parts of the request: method, headers, URI, extensions, etc. It does not touch the request body.
  • FromRequest - used when your extractor needs to consume the request body to produce its value. Examples built into Axum include Json<T>, String, Bytes, and Request.

Your custom extractor will implement FromRequest whenever it must read from the body stream. Once implemented, you can use your type directly as a handler argument, just like built-in extractors.

Mental model: Think of a request as a postal package. The envelope (address, stamps, labels) is the parts. The letter inside is the body. FromRequestParts reads the envelope. FromRequest opens the envelope and reads the letter.

When do you need FromRequest instead of FromRequestParts?

You need FromRequest if your extractor's result depends on the content of the request body. Common scenarios:

  • Parsing a custom binary format (not JSON or form).
  • Validating a raw string body against certain rules.
  • Reading and transforming the entire body before passing it on.
  • Combining body data with metadata from headers or state.

If you only need headers, query parameters, or other metadata, you would implement FromRequestParts instead. But once you touch the body, FromRequest is the trait to use.

A minimal starter example

Let's build the simplest possible custom body extractor: one that takes the entire request body and stores it as a String.

First, we define a struct that will hold the extracted data:

// This type will be our custom extractor.
pub struct BodyString(pub String);

Next, we implement FromRequest for it. We'll use axum::body::Bytes as a helper to read the raw body, then convert it to a String. Bytes is always available; there is no feature flag to enable for it.

Here is the complete code, including imports and a working route:

use axum::{
    extract::{FromRequest, Request},
    response::IntoResponse,
    routing::post,
    Router,
};
use axum::body::Bytes;
use axum::http::StatusCode;
use std::convert::Infallible;
// The custom extractor type.
pub struct BodyString(pub String);
// Implement FromRequest for BodyString.
// The generic `S` represents application state; we ignore it in this example.
impl<S> FromRequest<S> for BodyString
where
    S: Send + Sync,
{
    type Rejection = Infallible; // We never reject in this simple version.
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // Extract the body as Bytes, which implements FromRequest itself.
        // The `Bytes` extractor consumes the body, so we cannot use req afterwards.
        let bytes = Bytes::from_request(req, state).await.unwrap();
        // Convert bytes to a UTF-8 string.
        let body = String::from_utf8(bytes.to_vec()).unwrap();
        Ok(BodyString(body))
    }
}
// A handler that uses our custom extractor.
async fn echo_body(BodyString(body): BodyString) -> impl IntoResponse {
    format!("You sent: {body}")
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/echo", post(echo_body));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Everything works if...:

If you send a POST request to http://localhost:3000/echo with a text body, you'll see the response You sent: <your text>.

The starter example takes shortcuts:

The two .unwrap() calls in this first example will panic if the body is not valid UTF-8 or is larger than the default 2 MB limit. A panic inside a handler drops the connection without sending a response, so do not ship unwraps like these. The next section shows the proper pattern: a rejection type that turns each failure into a real HTTP response.

What's happening here? The from_request method receives the whole Request object and the application state. Inside, we call Bytes::from_request(req, state).await to get the raw body. Bytes is Axum's built-in extractor for reading the body as a byte buffer. It already knows how to consume the request body correctly (including respecting size limits). After we get the bytes, we convert them to a String and wrap it in our BodyString struct. The handler then receives our BodyString as an argument.

Why use Bytes? You could also use String::from_request(req, state).await directly, but Bytes gives you raw bytes. You then decide how to decode them. This is important when you need to handle non-UTF8 data or perform custom validation.

A crucial detail: Once you call Bytes::from_request(req, state), the original req is consumed and you cannot use it again. That's why we don't try to access headers after reading the body. We'll see later how to access headers before consuming the body.

Understanding the trait signature

Let's break down the FromRequest trait more carefully. The official definition looks like this (simplified):

pub trait FromRequest<S>: Sized {
    type Rejection: IntoResponse;
    fn from_request(
        req: Request,
        state: &S,
    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
}

In practice, you write a plain async fn in the impl block. The trait uses return-position impl Future (RPITIT), which stable Rust has supported since Rust 1.75, so no async_trait macro is needed. Do not add #[async_trait] to a FromRequest implementation: it changes the method signature and the code will not compile. The typical implementation starts with:

use axum::extract::FromRequest;
impl<S> FromRequest<S> for MyExtractor
where
    S: Send + Sync,
{
    type Rejection = MyRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // ...
    }
}

Key points:

  • S is the application state type. You can constrain it to Send + Sync if you don't need anything specific, but you can also require S: MyStateTrait if your extractor depends on state.
  • Rejection is the error type your extractor returns when extraction fails. It must implement IntoResponse. We'll cover this shortly.
  • The method takes the request by value, meaning it owns the request and can consume the body.

Why the where clause S: Send + Sync?:

Axum requires that application state be Send + Sync because handlers may run on different threads. When you implement FromRequest, you need to tell the compiler that your extractor works for any state that is Send + Sync. If you don't add this bound, you'll get an error because the trait implementation must be valid for all possible S that the handler might use.

A more realistic example: extracting and validating a body

Let's create an extractor that reads the body as bytes, ensures it's not empty, and then wraps it. We'll also define a proper rejection type so that if validation fails, Axum can return a meaningful error response.

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use axum::body::Bytes;
use axum::http::StatusCode;
// Extractor type.
pub struct NonEmptyBody(pub Bytes);
// Our custom rejection type.
pub enum NonEmptyBodyRejection {
    EmptyBody,
    BodyReadFailed(axum::extract::rejection::BytesRejection),
}
// Implement IntoResponse for the rejection.
impl IntoResponse for NonEmptyBodyRejection {
    fn into_response(self) -> Response {
        match self {
            NonEmptyBodyRejection::EmptyBody => {
                (StatusCode::BAD_REQUEST, "Request body cannot be empty").into_response()
            }
            NonEmptyBodyRejection::BodyReadFailed(err) => {
                (StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to read body: {err}")).into_response()
            }
        }
    }
}
// Implement FromRequest.
impl<S> FromRequest<S> for NonEmptyBody
where
    S: Send + Sync,
{
    type Rejection = NonEmptyBodyRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // Use the built-in Bytes extractor to read the body.
        let bytes = Bytes::from_request(req, state)
            .await
            .map_err(|err| NonEmptyBodyRejection::BodyReadFailed(err))?;
        if bytes.is_empty() {
            return Err(NonEmptyBodyRejection::EmptyBody);
        }
        Ok(NonEmptyBody(bytes))
    }
}
// Handler using our extractor.
async fn handle_non_empty(NonEmptyBody(body): NonEmptyBody) -> impl IntoResponse {
    format!("Received {} bytes", body.len())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/data", post(handle_non_empty));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

This example shows the full pattern for real-world use: a custom type, a custom rejection enum, mapping internal errors to rejections, and using the extractor in a handler.

Don't forget to handle the inner error:

When delegating to another extractor (like Bytes), the error type you get is not directly convertible to your rejection unless you explicitly map it. Always use map_err to convert the internal error into a variant of your rejection type. This keeps your API clean and gives users understandable responses.

Accessing request parts before consuming the body

One common requirement is to read headers or other metadata before you consume the body. With FromRequest, you receive the entire Request object, so you can inspect its parts first.

Let's create an extractor that checks a Content-Type header and only then reads the body. It will reject if the content type is not application/octet-stream or if the body is too large.

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use axum::body::Bytes;
use axum::http::{header, StatusCode};
pub struct VerifiedBytes(pub Bytes);
pub enum VerifiedBytesRejection {
    MissingContentType,
    WrongContentType,
    BodyReadFailed(axum::extract::rejection::BytesRejection),
}
impl IntoResponse for VerifiedBytesRejection {
    fn into_response(self) -> Response {
        match self {
            Self::MissingContentType => (
                StatusCode::BAD_REQUEST,
                "Content-Type header is required",
            ).into_response(),
            Self::WrongContentType => (
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                "Expected application/octet-stream",
            ).into_response(),
            Self::BodyReadFailed(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to read body: {err}"),
            ).into_response(),
        }
    }
}
impl<S> FromRequest<S> for VerifiedBytes
where
    S: Send + Sync,
{
    type Rejection = VerifiedBytesRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // 1. Check headers first (request parts are still available).
        let content_type = req
            .headers()
            .get(header::CONTENT_TYPE)
            .ok_or(Self::Rejection::MissingContentType)?;
        if content_type != "application/octet-stream" {
            return Err(Self::Rejection::WrongContentType);
        }
        // 2. Now consume the body using Bytes.
        let bytes = Bytes::from_request(req, state)
            .await
            .map_err(Self::Rejection::BodyReadFailed)?;
        Ok(VerifiedBytes(bytes))
    }
}
async fn upload(VerifiedBytes(data): VerifiedBytes) -> impl IntoResponse {
    format!("Uploaded {} bytes", data.len())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/upload", post(upload));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Notice that we access req.headers() before calling Bytes::from_request. This is perfectly fine because we haven't consumed the request yet. After we call Bytes::from_request(req, ...), we cannot use req again - so we must extract everything we need from the parts first.

Accessing request after consuming body causes compile error:

If you try to use req after calling an extractor that consumes the body (like Bytes, String, Json), you will get a move error. Rust prevents this because the Request was moved into the extractor call. Always read what you need from req before consuming the body.

Delegating to another body extractor

You don't have to manually call Bytes::from_request. You can delegate to any type that already implements FromRequest. For instance, if you want to create an extractor that works with JSON but adds extra validation, you can wrap Json<T>.

Here's an extractor that expects a JSON object and verifies a field is present and non-empty. We'll use axum::Json inside.

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    routing::post,
    Router, Json,
};
use serde::Deserialize;
use axum::http::StatusCode;
#[derive(Deserialize)]
pub struct UserInput {
    pub username: String,
    pub email: String,
}
// Custom extractor that validates the input.
pub struct ValidUser(pub UserInput);
pub enum ValidUserRejection {
    JsonRejection(axum::extract::rejection::JsonRejection),
    InvalidUsername,
    InvalidEmail,
}
impl IntoResponse for ValidUserRejection {
    fn into_response(self) -> Response {
        match self {
            Self::JsonRejection(rejection) => rejection.into_response(),
            Self::InvalidUsername => (
                StatusCode::BAD_REQUEST,
                "Username must not be empty",
            ).into_response(),
            Self::InvalidEmail => (
                StatusCode::BAD_REQUEST,
                "Email must contain @",
            ).into_response(),
        }
    }
}
impl<S> FromRequest<S> for ValidUser
where
    S: Send + Sync,
{
    type Rejection = ValidUserRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // Delegate to Json<UserInput> extractor.
        let Json(user_input) = Json::<UserInput>::from_request(req, state)
            .await
            .map_err(ValidUserRejection::JsonRejection)?;
        if user_input.username.trim().is_empty() {
            return Err(ValidUserRejection::InvalidUsername);
        }
        if !user_input.email.contains('@') {
            return Err(ValidUserRejection::InvalidEmail);
        }
        Ok(ValidUser(user_input))
    }
}
async fn register(ValidUser(user): ValidUser) -> impl IntoResponse {
    format!("Welcome, {}", user.username)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/register", post(register));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

This approach is extremely powerful: you can reuse Axum's built-in extractors (with their full error types) and then add your own custom validation logic on top. The rejection type can forward the original rejection or transform it.

Using built-in rejections in your custom rejection:

If you want the exact same error response that Json would produce on failure, just call .into_response() on the JsonRejection variant. This keeps consistent behavior between your custom extractor and the standard one.

Multiple ways to implement the same extractor

There are often several valid approaches. Let's compare two ways to build a BodyUpperCase extractor that reads the body as a string and uppercases it.

Approach 1: Use String extractor directly

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
pub struct BodyUpperCase(pub String);
pub enum BodyUpperCaseRejection {
    ReadError(axum::extract::rejection::StringRejection),
}
impl IntoResponse for BodyUpperCaseRejection {
    fn into_response(self) -> Response {
        match self {
            Self::ReadError(err) => err.into_response(),
        }
    }
}
impl<S> FromRequest<S> for BodyUpperCase
where
    S: Send + Sync,
{
    type Rejection = BodyUpperCaseRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // Use String extractor (requires UTF-8).
        let body = String::from_request(req, state)
            .await
            .map_err(Self::Rejection::ReadError)?;
        Ok(BodyUpperCase(body.to_uppercase()))
    }
}
async fn handler(BodyUpperCase(upper): BodyUpperCase) -> impl IntoResponse {
    upper
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/upper", post(handler));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The String extractor already rejects bodies that are not valid UTF-8, so this approach needs no separate check for that case. When the body contains invalid UTF-8, the forwarded rejection answers with a 400 whose body starts with Request body didn't contain valid UTF-8, and a body over the default limit gets a 413. Forwarding the built-in rejection keeps those exact statuses instead of replacing them with a generic error of your own.

Approach 2: Use Bytes and then convert manually

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use axum::body::Bytes;
use axum::http::StatusCode;
pub struct BodyUpperCase(pub String);
pub enum BodyUpperCaseRejection {
    ReadError(axum::extract::rejection::BytesRejection),
    NotUtf8,
}
impl IntoResponse for BodyUpperCaseRejection {
    fn into_response(self) -> Response {
        match self {
            Self::ReadError(err) => err.into_response(),
            Self::NotUtf8 => (
                StatusCode::BAD_REQUEST,
                "Body must be valid UTF-8",
            )
                .into_response(),
        }
    }
}
impl<S> FromRequest<S> for BodyUpperCase
where
    S: Send + Sync,
{
    type Rejection = BodyUpperCaseRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let bytes = Bytes::from_request(req, state)
            .await
            .map_err(Self::Rejection::ReadError)?;
        let body = String::from_utf8(bytes.to_vec())
            .map_err(|_| Self::Rejection::NotUtf8)?;
        Ok(BodyUpperCase(body.to_uppercase()))
    }
}
async fn handler(BodyUpperCase(upper): BodyUpperCase) -> impl IntoResponse {
    upper
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/upper", post(handler));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here the UTF-8 check is yours to write, because Bytes hands you raw bytes and never looks at their meaning. A body of invalid UTF-8 reaches the String::from_utf8 call and comes back as your own 400 with the message Body must be valid UTF-8. A body that fails to buffer is still forwarded as the built-in BytesRejection, so an over-limit body gets its normal 413.

Both produce the same result, but the first is simpler when you know the body is UTF-8. The second gives you more control. With raw bytes in hand you can handle a different encoding, strip a byte-order mark before converting, or reject bytes that are valid UTF-8 but not allowed in your format. Pick the first approach when the String extractor already checks everything you need, and the second when you need to inspect or transform the bytes before deciding what they mean.

Which approach should you choose?:

Use the most specific built-in extractor that fits your needs. If you need raw bytes for binary processing, use Bytes. If you need a UTF-8 string, use String. If you need JSON, use Json<T>. Delegation keeps your code short and lets Axum handle low-level concerns like body limits and streaming.

Accessing application state in a custom extractor

Sometimes your extractor needs to read data from application state. Since FromRequest gives you &S, you can access it before or after consuming the body.

Suppose you have a configuration value (like a maximum allowed body size) stored in state. The first thing to understand is that the state argument inside from_request is not your concrete state struct. It is the generic &S, so the compiler has no idea which fields your state has. Reading a field straight off it does not compile:

// This does NOT compile: `state` is the generic `&S`, not `&AppState`,
// so the compiler has no idea that `S` has a `max_body_bytes` field.
let max = state.max_body_bytes;
error[E0609]: no field `max_body_bytes` on type `&S`

Accessing typed state generically in FromRequest requires a trait bound on S. A common alternative is to not implement FromRequest when you need state, and instead use State<AppState> as a separate handler argument or use middleware. But when the extractor itself needs the state, define a trait for it and require it in the where clause. Here is the correct way using a trait:

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use axum::body::Bytes;
use axum::http::StatusCode;
// Define a trait that state must implement.
pub trait MaxBodySize {
    fn max_body_bytes(&self) -> usize;
}
// Our state will implement this trait.
#[derive(Clone)]
pub struct AppState {
    pub max_body_bytes: usize,
}
impl MaxBodySize for AppState {
    fn max_body_bytes(&self) -> usize {
        self.max_body_bytes
    }
}
pub struct LimitedBody(pub Bytes);
pub enum LimitedBodyRejection {
    TooLarge,
    ReadFailed(axum::extract::rejection::BytesRejection),
}
impl IntoResponse for LimitedBodyRejection {
    fn into_response(self) -> Response {
        match self {
            Self::TooLarge => (
                StatusCode::PAYLOAD_TOO_LARGE,
                "Body exceeds maximum allowed size",
            )
                .into_response(),
            Self::ReadFailed(e) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to read body: {e}"),
            )
                .into_response(),
        }
    }
}
impl<S> FromRequest<S> for LimitedBody
where
    S: MaxBodySize + Send + Sync,
{
    type Rejection = LimitedBodyRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let max = state.max_body_bytes();
        // We need to read the body, but we also want to enforce max size.
        // We can't easily limit during reading unless we use a custom body stream,
        // but we can read all bytes and then check length.
        let bytes = Bytes::from_request(req, state)
            .await
            .map_err(LimitedBodyRejection::ReadFailed)?;
        if bytes.len() > max {
            return Err(LimitedBodyRejection::TooLarge);
        }
        Ok(LimitedBody(bytes))
    }
}
async fn upload(LimitedBody(data): LimitedBody) -> impl IntoResponse {
    format!("Accepted {} bytes", data.len())
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/upload", post(upload))
        .with_state(AppState { max_body_bytes: 1024 });
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The router is built with .with_state(AppState { max_body_bytes: 1024 }), so every request to /upload runs the extractor with that limit. A small body comes back as Accepted 2 bytes, and a body over 1024 bytes gets a 413 with Body exceeds maximum allowed size.

Note that this checks the size after reading the whole body, which is not ideal for very large bodies. But for simplicity, it's acceptable.

State access in FromRequest requires a trait bound:

You cannot directly use a concrete state type in a generic FromRequest implementation because the trait is implemented for all S that satisfy the bounds. If you need to access state, define a trait that provides the needed methods and add it to the where clause. This is a common pattern in Axum.

Using Request directly without delegating

Sometimes you need full control over the request body. Instead of using Bytes or String, you can consume the body yourself with the http-body-util crate (add http-body-util = "0.1" to Cargo.toml). Axum re-exports axum::body::Body, but the simplest is still to use built-in extractors. It is good to know how to do it manually, though.

Here is an extractor that reads the body as a stream and collects it into a Vec<u8>:

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use axum::http::StatusCode;
use http_body_util::BodyExt;
pub struct RawVec(pub Vec<u8>);
pub enum RawVecRejection {
    ReadFailed(axum::Error),
}
impl IntoResponse for RawVecRejection {
    fn into_response(self) -> Response {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to read body",
        )
            .into_response()
    }
}
impl<S> FromRequest<S> for RawVec
where
    S: Send + Sync,
{
    type Rejection = RawVecRejection;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let _ = state;
        // Take the body out of the request and collect the stream into bytes.
        // (Older hyper 0.14 code used `hyper::body::to_bytes`; that function
        // does not exist in hyper 1.x.)
        let body = req.into_body();
        let bytes = body
            .collect()
            .await
            .map_err(RawVecRejection::ReadFailed)?
            .to_bytes();
        Ok(RawVec(bytes.to_vec()))
    }
}

This is more low-level, but you rarely need it. The Bytes extractor does exactly this under the hood, with additional size limit handling.

Common mistakes and misconceptions

  • Forgetting Send + Sync bound on S: This causes compile errors. Always include where S: Send + Sync unless you have a more specific bound.
  • Using the request after consuming the body: Rust's move semantics prevent this, but it's a common logical error when planning your code.
  • Not mapping errors from delegated extractors: If you use ? on Bytes::from_request result, the error type must match your rejection type. Often you need map_err.
  • Consuming the body twice: You cannot call another body extractor after you've already consumed the body. Only one body-consuming extractor is allowed per handler.
  • Assuming the body is always UTF-8: String::from_utf8 returns a Result, and calling .unwrap() on it panics when the body holds invalid bytes. Handle the Err case with your own rejection, or use String::from_utf8_lossy when replacing bad bytes with the replacement character is acceptable.
  • Not handling size limits: Axum's default body limit applies to built-in extractors, but if you read the body manually, you might bypass it. Always use a built-in body extractor if possible.

Multiple body extractors in one handler:

A handler can have at most one extractor that implements FromRequest (consumes the body). All other extractors must implement FromRequestParts. If you try to use two body extractors, the code will not compile. This is enforced by Axum's trait design.

Do not use async_trait for FromRequest

Older Axum versions (0.6 and earlier) required the async_trait macro to implement async traits on stable Rust. Axum 0.8 does not. The FromRequest trait uses return-position impl Future, which stable Rust supports natively since Rust 1.75, and Axum's minimum supported Rust version is 1.80. Write a plain async fn in your impl block, exactly as in every example on this page.

In particular, do not write this:

use axum::extract::{FromRequest, Request};
use axum::async_trait; // does not exist: axum 0.8 does not re-export async_trait
pub struct MyExtractor;
#[async_trait]
impl<S> FromRequest<S> for MyExtractor
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;
    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let _ = (req, state);
        Ok(MyExtractor)
    }
}

That code fails to compile in two ways: axum::async_trait does not exist in axum 0.8, and even with the async-trait crate added directly, the macro changes the method signature so it no longer matches the trait. The native async fn form is the only correct one.

Summary

Implementing a custom FromRequest extractor gives you full control over how request bodies are parsed and validated. You can delegate to existing extractors like Bytes, String, or Json, or handle the body manually. Always define a clear rejection type that implements IntoResponse so your API returns meaningful errors. Remember to read any request parts before consuming the body, and respect the one-body-extractor rule.

This capability unlocks a whole category of domain-specific extractors: you can create extractors for XML, CSV, custom binary protocols, or even encrypted payloads. The pattern remains the same: implement the trait, consume the body, validate, and return your type.