Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Extractors and Responses

Custom Extractors and Rejections in Axum

Write your own Axum extractors with FromRequestParts and FromRequest, return JSON rejections, wrap Json for validation, and understand extractor order and the macros.

The built-in extractors cover a lot, but every real application grows its own: the authenticated user, an API key, a tenant taken from the subdomain, JSON that is already validated. Writing your own extractor turns a repeated block of handler code into one argument type, and it keeps handlers short and focused.

You will also learn how to change the rejection: the response Axum sends when extraction fails. The default rejections are plain text, which is rarely what an API wants.

The two traits

An extractor is any type that implements one of these traits:

Trait Gets Use for
FromRequestParts<S> the request head (&mut Parts: method, URI, headers, extensions) and the state S anything that does not need the body
FromRequest<S> the whole Request, body included body parsers; consumes the request

Each has an associated type Rejection: IntoResponse. On failure you return Err(rejection), and Axum turns it into the response without calling the handler. In Axum 0.8 these traits use native async fn in traits, so you no longer need the #[async_trait] attribute from older tutorials.

Example: an API key extractor

Rust
use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
};

struct ApiKey(String);

impl<S> FromRequestParts<S> for ApiKey
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let value = parts
            .headers
            .get("x-api-key")
            .and_then(|v| v.to_str().ok())
            .ok_or((StatusCode::UNAUTHORIZED, "missing x-api-key header"))?;

        if value.len() < 8 {
            return Err((StatusCode::UNAUTHORIZED, "malformed api key"));
        }
        Ok(ApiKey(value.to_string()))
    }
}

async fn whoami(ApiKey(key): ApiKey) -> String {
    format!("key ends with ...{}", &key[key.len() - 4..])
}

Any handler that lists ApiKey as an argument now requires the header, and none of them repeats the check. Because the rejection is a tuple that implements IntoResponse, the client gets 401 and the message.

Using state inside an extractor

The _state parameter is the router state. Constrain S so you can reach what you need, the usual trick for authentication:

Rust
impl<S> FromRequestParts<S> for CurrentUser
where
    AppState: axum::extract::FromRef<S>,
    S: Send + Sync,
{
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let app = AppState::from_ref(state);
        // read the token header, look it up in app.db, return the user or an error
        todo!()
    }
}

Shared state explains FromRef; the authentication chapter completes this extractor.

Changing rejections of built-in extractors

The default text rejection of Json<T> or Path<T> is fine for a prototype and wrong for an API with a JSON error contract. Three approaches, from least to most work:

  1. WithRejection (from axum-extra): WithRejection<Json<T>, ApiError> runs the normal extractor and converts its rejection into ApiError through From.

  2. #[derive(FromRequest)] (feature macros): wrap the built-in extractor in a struct and name your rejection type.

    Rust
    use axum::extract::FromRequest;
    
    #[derive(FromRequest)]
    #[from_request(via(axum::Json), rejection(ApiError))]
    struct AppJson<T>(T);
    

    The rejection type needs From<JsonRejection>.

  3. Implement the trait by hand, as below, when you also want validation.

A validating JSON extractor

Rust
use axum::{extract::{rejection::JsonRejection, FromRequest, Request}, Json};
use serde::de::DeserializeOwned;

trait Validate { fn validate(&self) -> Result<(), String>; }

struct ValidatedJson<T>(T);

impl<S, T> FromRequest<S> for ValidatedJson<T>
where
    T: DeserializeOwned + Validate,
    S: Send + Sync,
{
    type Rejection = ApiError;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let Json(value) = Json::<T>::from_request(req, state)
            .await
            .map_err(|e: JsonRejection| ApiError::bad_request(e.body_text()))?;
        value.validate().map_err(ApiError::unprocessable)?;
        Ok(ValidatedJson(value))
    }
}

async fn create_user(ValidatedJson(user): ValidatedJson<NewUser>) -> String {
    format!("creating {}", user.name) // already validated here
}

The handler body has no if for bad input at all. This is the main benefit of custom extractors: the type of the argument states a guarantee.

Extractor order and the Option / Result wrappers

  • Extractors run left to right. If the first fails, later ones never run. Put cheap checks (authentication) before body parsing.
  • Wrap an extractor in Option<T> to make it optional: a failure becomes None. Since Axum 0.8 this only works for extractors that implement OptionalFromRequestParts; the built-in Query, Path (for optional segments) and the typed header extractors do.
  • Wrap it in Result<T, T::Rejection> to handle the failure inside the handler:
Rust
async fn lenient(page: Result<Query<Page>, QueryRejection>) -> String {
    match page {
        Ok(Query(p)) => format!("page {}", p.page),
        Err(e) => format!("bad query, using defaults ({})", e.body_text()),
    }
}

Stand-in: extractors as a trait

The real traits are async and generic over the request type. This model keeps the idea: an Extractor trait with an associated error, a request made of headers and a body, and handlers that gather their arguments in order, stopping at the first rejection.

Rust Stand-in: extractors, rejections and short-circuiting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice the last line: when two extractors would fail, the first one decides the response. That is also why authentication extractors belong before body extractors: an anonymous client never makes you parse a large body.

Stand-in: turning rejections into one JSON error shape

A consistent error body is the second reason to customise rejections. The model maps three different internal rejection kinds into one ApiError through From, exactly the pattern WithRejection and #[from_request(rejection(...))] rely on.

Rust Stand-in: many rejections, one error shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Common mistakes

  • Putting a body extractor before others: the code will not compile, with a long error about the Handler trait. #[axum::debug_handler] makes that error readable.
  • Doing slow work (database lookups) in an extractor that every route uses. Extractors run on every request that lists them.
  • Returning 500 for bad client input. Pick the status that matches the cause: 400, 401, 403, 415 or 422.
  • Forgetting Send + Sync bounds on the state parameter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which trait should an extractor implement if it only needs headers and the URI?

    FromRequestParts sees only the request head, so several such extractors can appear in one handler in any order.
  2. 2. What type must an extractor's Rejection implement?

    Axum turns the rejection into the HTTP response when extraction fails.
  3. 3. A handler has two failing extractors, ApiKey first and a JSON body second. Which rejection does the client get?

    Extraction short-circuits. That is why cheap authentication checks should come before body parsing.
  4. 4. How can you make the built-in Json<T> return your own JSON error type on failure?

    WithRejection and the derive macro both convert JsonRejection into your own type through From.

Summary

  • Implement FromRequestParts for head-only extractors and FromRequest for ones that consume the body.
  • Failures return Err(Rejection); the rejection implements IntoResponse, and the handler is skipped.
  • Use WithRejection or #[derive(FromRequest)] to give built-in extractors your own error shape.
  • Extractors run left to right and stop at the first failure; Option<T> and Result<T, E> let handlers cope with failures.
  • A ValidatedJson<T> style extractor makes the handler's argument type a guarantee.

Next: Headers, Cookies and Uploads