Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Routers and Handlers

Axum Handler Functions and the Handler Trait

Understand what makes an async function an Axum handler: extractor arguments, the body-consuming last argument, IntoResponse return types, closures, and how to read handler errors.

A handler is the function that runs when a route matches. In Axum almost any async fn can be a handler, as long as it follows two rules: every argument is an extractor (something Axum knows how to build from the request) and the return type implements IntoResponse (something Axum knows how to turn into a response). There is no base class, no macro on the function and no special signature.

This lesson explains those rules, why Axum can accept functions with zero, one or sixteen arguments, and how to decode the infamous "the trait Handler is not implemented" error. You will also run a small model of the machinery that makes it work.

The shape of a handler

Rust
use axum::{extract::Path, http::StatusCode, Json};
use serde::Serialize;

#[derive(Serialize)]
struct User {
    id: u32,
    name: String,
}

async fn get_user(Path(id): Path<u32>) -> Result<Json<User>, StatusCode> {
    if id == 1 {
        Ok(Json(User { id, name: "Ada".into() }))
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}
  • Path(id): Path<u32> is an extractor in the argument list. Axum pulls the segment from the URL and parses it as a u32. If parsing fails, the handler never runs and the client gets a 400.
  • The return type Result<Json<User>, StatusCode> works because Result<T, E> implements IntoResponse when both T and E do. Ok becomes a JSON 200, Err becomes a bare 404.

A handler with no arguments is fine too (async fn health() -> &'static str), and so is a closure: get(|| async { "hi" }).

The rules in detail

  1. It must be async. The function (or closure) returns a future.
  2. At most 16 arguments. Enough for any sane handler.
  3. Every argument implements FromRequestParts or FromRequest. Extractors such as Path, Query, State, HeaderMap and Extension only look at the request head and can appear in any position. Extractors that consume the body (Json, Form, String, Bytes, Request) implement FromRequest and must be last, because the body can be read only once.
  4. The future must be Send. Tokio may move it between threads, so you cannot hold a non-Send value (such as a std::sync::MutexGuard or an Rc) across an .await.
  5. The return type implements IntoResponse. See responses.
  6. Everything in the signature is 'static. Handlers cannot borrow from local variables; clone cheap data or use shared state.

Order of extractors matters in exactly one way: body-consuming extractors go last.

Rust
use axum::{extract::{Path, Query, State}, Json};

// Good: parts extractors first, Json last.
async fn update(
    State(state): State<AppState>,
    Path(id): Path<u32>,
    Query(opts): Query<Options>,
    Json(body): Json<NewNote>,
) -> String {
    format!("updating {id}")
}

How can one get(...) accept any signature?

Axum implements the Handler trait for functions of every arity using a macro. In simplified form:

Rust
pub trait Handler<T, S>: Clone + Send + Sized + 'static {
    type Future: Future<Output = Response> + Send + 'static;
    fn call(self, req: Request, state: S) -> Self::Future;
}

// Implemented (via macro) for F where
//   F: FnOnce(A, B, ...) -> Fut, Fut: Future<Output = R>,
//   A, B, ...: FromRequest..., R: IntoResponse

The type parameter T is a tuple of the argument types; it exists so the compiler can tell the implementations for different arities apart.

A runnable model of that machinery

This stand-in (no async, to keep it short) shows the idea: Handler is implemented for functions taking zero, one or two extractor arguments, and route() turns any of them into a uniform boxed function from Request to Response. If an extractor fails, the handler is skipped and an error response is returned, just like a rejection.

Rust Stand-in: a Handler trait implemented for many arities

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.

The parts to notice: health takes no arguments and update takes two, yet all three go through the same route. The Err(rejection) branch is Axum's rejection: when an extractor fails, the response it describes is returned and your function body never runs.

A handler that uses ?

Because Result<T, E> implements IntoResponse when E does, handlers can use ? to bail out early. In practice E is your own error type, covered in error handling. A taste, modelled in plain Rust:

Rust Stand-in: early return with ? and an error that becomes a response

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.

Reading handler errors

When a function is not a valid handler, the compiler says something like:

TEXT
error[E0277]: the trait bound `fn(Foo) -> impl Future<Output = ()> {handler}: Handler<_, _>` is not satisfied

It does not say why. Check this list:

  1. Is the function async?
  2. Is every argument an extractor (Path<T>, Query<T>, State<T>, Json<T> ...)? A plain String or u32 argument is not an extractor.
  3. Is the body-consuming extractor last?
  4. Does the return type implement IntoResponse? () does, Result<(), E> needs E: IntoResponse, and a custom struct does not until you implement it.
  5. Is the future Send? A MutexGuard held across .await is the classic culprit.

Add axum-macros and put #[axum::debug_handler] on the function: the macro re-checks each rule and reports the exact failing one, in plain language. Remove it when done; it is a development aid.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must an extractor that consumes the request body (like Json<T>) appear?

    Body extractors implement FromRequest and must be the final argument.
  2. 2. Which of these is NOT a valid handler argument?

    Arguments must be extractors; a bare u32 does not implement FromRequest.
  3. 3. Why can't a handler hold a std::sync::MutexGuard across an .await?

    Tokio may move the future between threads, so everything alive across .await must be Send.
  4. 4. What does #[axum::debug_handler] do?

    It is a development aid that checks the handler rules and reports the exact violation.

Summary

  • A handler is an async fn whose arguments are extractors and whose return type implements IntoResponse.
  • Extractors that read the body go last; the future must be Send and 'static.
  • Result<T, E> is a valid return type, so ? works inside handlers.
  • When the compiler complains about Handler, walk the checklist or use #[axum::debug_handler].

Next: Path Parameters and Wildcards