Trait Handler

trait Handler<T, S>: Clone + Send + Sync + Sized + 'static

Trait for async functions that can be used to handle requests.

You shouldn't need to depend on this trait directly. It is automatically implemented to closures of the right types.

See the module docs for more details.

Converting Handlers into Services

To convert Handlers into Services you have to call either HandlerWithoutStateExt::into_service or [Handler::with_state]:

use tower::Service;
use axum::{
    extract::{State, Request},
    body::Body,
    handler::{HandlerWithoutStateExt, Handler},
};

// this handler doesn't require any state
async fn one() {}
// so it can be converted to a service with `HandlerWithoutStateExt::into_service`
assert_service(one.into_service());

// this handler requires state
async fn two(_: State<String>) {}
// so we have to provide it
let handler_with_state = two.with_state(String::new());
// which gives us a `Service`
assert_service(handler_with_state);

// helper to check that a value implements `Service`
fn assert_service<S>(service: S)
where
    S: Service<Request>,
{}

Debugging handler type errors

For a function to be used as a handler it must implement the Handler trait. axum provides blanket implementations for functions that:

Unfortunately Rust gives poor error messages if you try to use a function that doesn't quite match what's required by Handler.

You might get an error like this:

error[E0277]: the trait bound `fn(bool) -> impl Future {handler}: Handler<_, _>` is not satisfied
   --> src/main.rs:13:44
    |
13  |     let app = Router::new().route("/", get(handler));
    |                                            ^^^^^^^ the trait `Handler<_, _>` is not implemented for `fn(bool) -> impl Future {handler}`
    |
   ::: axum/src/handler/mod.rs:116:8
    |
116 |     H: Handler<T, B>,
    |        ------------- required by this bound in `axum::routing::get`

This error doesn't tell you why your function doesn't implement Handler. It's possible to improve the error with the debug_handler proc-macro from the axum-macros crate.

Handlers that aren't functions

The Handler trait is also implemented for T: IntoResponse. That allows easily returning fixed data for routes:

use axum::{
    Router,
    routing::{get, post},
    Json,
    http::StatusCode,
};
use serde_json::json;

let app = Router::new()
    // respond with a fixed string
    .route("/", get("Hello, World!"))
    // or return some mock data
    .route("/users", post((
        StatusCode::CREATED,
        Json(json!({ "id": 1, "username": "alice" })),
    )));
# let _: Router = app;

Associated Types

type Future: TraitBound { trait_: Path { path: "Future", id: Id(77), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Output", args: None, binding: Equality(Type(ResolvedPath(Path { path: "Response", id: Id(139), args: None }))) }] }) }, generic_params: [], modifier: None } + TraitBound { trait_: Path { path: "Send", id: Id(5), args: None }, generic_params: [], modifier: None } + Outlives("'static")

The type of future calling this handler returns.

Required Methods

fn call(self: Self, req: Request, state: S) -> <Self as >::Future

Call the handler with the given request.

Provided Methods

fn layer<L>(self: Self, layer: L) -> Layered<L, Self, T, S>
where
    L: Layer<HandlerService<Self, T, S>> + Clone,
    <L as >::Service: Service<Request>

Apply a tower::Layer to the handler.

All requests to the handler will be processed by the layer's corresponding middleware.

This can be used to add additional processing to a request for a single handler.

Note this differs from routing::Router::layer which adds a middleware to a group of routes.

If you're applying middleware that produces errors you have to handle the errors so they're converted into responses. You can learn more about doing that here.

Example

Adding the tower::limit::ConcurrencyLimit middleware to a handler can be done like so:

use axum::{
    routing::get,
    handler::Handler,
    Router,
};
use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};

async fn handler() { /* ... */ }

let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64));
let app = Router::new().route("/", get(layered_handler));
# let _: Router = app;
fn with_state(self: Self, state: S) -> HandlerService<Self, T, S>

Convert the handler into a Service by providing the state

Implementors