# axum 0.8.9

> axum is an HTTP routing and request-handling library that focuses on ergonomics and modularity.

## axum

axum is an HTTP routing and request-handling library that focuses on ergonomics and modularity.

### axum › High-level features

- Route requests to handlers with a macro-free API.
- Declaratively parse requests using extractors.
- Simple and predictable error handling model.
- Generate responses with minimal boilerplate.
- Take full advantage of the [`tower`] and [`tower-http`] ecosystem of
  middleware, services, and utilities.

In particular, the last point is what sets `axum` apart from other libraries / frameworks.
`axum` doesn't have its own middleware system but instead uses
[`tower::Service`]. This means `axum` gets timeouts, tracing, compression,
authorization, and more, for free. It also enables you to share middleware with
applications written using [`hyper`] or [`tonic`].

### axum › Compatibility

axum is designed to work with [tokio] and [hyper]. Runtime and
transport layer independence is not a goal, at least for the time being.

### axum › Example

The "Hello, World!" of axum is:

```rust,no_run
use axum::{
    routing::get,
    Router,
};

#[tokio::main]
async fn main() {
    // build our application with a single route
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));

    // run our app with hyper, listening globally on port 3000
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

Note using `#[tokio::main]` requires you enable tokio's `macros` and `rt-multi-thread` features
or just `full` to enable all features (`cargo add tokio --features macros,rt-multi-thread`).

### axum › Routing

[`Router`] is used to set up which paths go to which services:

```rust
use axum::{Router, routing::get};

// our router
let app = Router::new()
    .route("/", get(root))
    .route("/foo", get(get_foo).post(post_foo))
    .route("/foo/bar", get(foo_bar));

// which calls one of these handlers
async fn root() {}
async fn get_foo() {}
async fn post_foo() {}
async fn foo_bar() {}
# let _: Router = app;
```

See [`Router`] for more details on routing.

### axum › Handlers

In axum a "handler" is an async function that accepts zero or more
["extractors"](crate::extract) as arguments and returns something that
can be converted [into a response](crate::response).

Handlers are where your application logic lives and axum applications are built
by routing between handlers.

[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html

See [`handler`](crate::handler) for more details on handlers.

### axum › Extractors

An extractor is a type that implements [`FromRequest`] or [`FromRequestParts`]. Extractors are
how you pick apart the incoming request to get the parts your handler needs.

```rust
use axum::extract::{Path, Query, Json};
use std::collections::HashMap;

// `Path` gives you the path parameters and deserializes them.
async fn path(Path(user_id): Path<u32>) {}

// `Query` gives you the query parameters and deserializes them.
async fn query(Query(params): Query<HashMap<String, String>>) {}

// Buffer the request body and deserialize it as JSON into a
// `serde_json::Value`. `Json` supports any type that implements
// `serde::Deserialize`.
async fn json(Json(payload): Json<serde_json::Value>) {}
```

See [`extract`](crate::extract) for more details on extractors.

### axum › Responses

Anything that implements [`IntoResponse`] can be returned from handlers.

```rust,no_run
use axum::{
    body::Body,
    routing::get,
    response::Json,
    Router,
};
use serde_json::{Value, json};

// `&'static str` becomes a `200 OK` with `content-type: text/plain; charset=utf-8`
async fn plain_text() -> &'static str {
    "foo"
}

// `Json` gives a content-type of `application/json` and works with any type
// that implements `serde::Serialize`
async fn json() -> Json<Value> {
    Json(json!({ "data": 42 }))
}

let app = Router::new()
    .route("/plain_text", get(plain_text))
    .route("/json", get(json));
# let _: Router = app;
```

See [`response`](crate::response) for more details on building responses.

### axum › Error handling

axum aims to have a simple and predictable error handling model. That means
it is simple to convert errors into responses and you are guaranteed that
all errors are handled.

See [`error_handling`] for more details on axum's
error handling model and how to handle errors gracefully.

### axum › Middleware

There are several different ways to write middleware for axum. See
[`middleware`] for more details.

### axum › Sharing state with handlers

It is common to share some state between handlers. For example, a
pool of database connections or clients to other services may need to
be shared.

The four most common ways of doing that are:

- Using the [`State`] extractor
- Using request extensions
- Using closure captures
- Using task-local variables

### axum › Using the [`State`] extractor

```rust,no_run
use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::Arc;

struct AppState {
    // ...
}

let shared_state = Arc::new(AppState { /* ... */ });

let app = Router::new()
    .route("/", get(handler))
    .with_state(shared_state);

async fn handler(
    State(state): State<Arc<AppState>>,
) {
    // ...
}
# let _: Router = app;
```

State is cloned for every request. Wrapping your state in `Arc` makes those
clones cheap. If all fields are already cheap to clone (for example, each field
is itself an `Arc` or a copy type), you can `#[derive(Clone)]` directly on the
struct instead.

### axum › Substates with `FromRef`

When a handler only needs part of the application state, use [`FromRef`] to extract
a substate. Implement the trait manually, or derive it with `#[derive(FromRef)]`
(requires the `macros` feature):

```rust
use axum::{Router, routing::get, extract::{State, FromRef}};

#[derive(Clone)]
struct AppState {
    api_state: ApiState,
}

#[derive(Clone)]
struct ApiState {}

// Teach axum how to produce an `ApiState` from a reference to `AppState`.
impl FromRef<AppState> for ApiState {
    fn from_ref(app_state: &AppState) -> ApiState {
        app_state.api_state.clone()
    }
}

let app = Router::new()
    .route("/", get(handler))
    .with_state(AppState { api_state: ApiState {} });

// This handler receives only the `ApiState` slice; it never sees `AppState`.
async fn handler(State(api_state): State<ApiState>) {}
# let _: Router = app;
```

### axum › The `Router<S>` type parameter

`Router<S>` when `S` is not `()` means a router that is _missing_ a state of type `S`. Calling
[`.with_state(s)`][Router::with_state] provides that state and typically produces a
`Router<()>`, which is the only form that can be passed to [`serve()`]. See
[`Router::with_state`] for a full explanation.

You should prefer using [`State`] if possible since it's more type safe. The downside is that
it's less dynamic than task-local variables and request extensions.

See [`State`] for more details about accessing state.

### axum › Using request extensions

Another way to share state with handlers is using [`Extension`] as
layer and extractor:

```rust,no_run
use axum::{
    extract::Extension,
    routing::get,
    Router,
};
use std::sync::Arc;

struct AppState {
    // ...
}

let shared_state = Arc::new(AppState { /* ... */ });

let app = Router::new()
    .route("/", get(handler))
    .layer(Extension(shared_state));

async fn handler(
    Extension(state): Extension<Arc<AppState>>,
) {
    // ...
}
# let _: Router = app;
```

The downside to this approach is that you'll get runtime errors
(specifically a `500 Internal Server Error` response) if you try and extract
an extension that doesn't exist, perhaps because you forgot to add the
middleware or because you're extracting the wrong type.

### axum › Using closure captures

State can also be passed directly to handlers using closure captures:

```rust,no_run
use axum::{
    Json,
    extract::{Extension, Path},
    routing::{get, post},
    Router,
};
use std::sync::Arc;
use serde::Deserialize;

struct AppState {
    // ...
}

let shared_state = Arc::new(AppState { /* ... */ });

let app = Router::new()
    .route(
        "/users",
        post({
            let shared_state = Arc::clone(&shared_state);
            move |body| create_user(body, shared_state)
        }),
    )
    .route(
        "/users/{id}",
        get({
            let shared_state = Arc::clone(&shared_state);
            move |path| get_user(path, shared_state)
        }),
    );

async fn get_user(Path(user_id): Path<String>, state: Arc<AppState>) {
    // ...
}

async fn create_user(Json(payload): Json<CreateUserPayload>, state: Arc<AppState>) {
    // ...
}

#[derive(Deserialize)]
struct CreateUserPayload {
    // ...
}
# let _: Router = app;
```

The downside to this approach is that it's the most verbose approach.

### axum › Using task-local variables

This also allows to share state with `IntoResponse` implementations:

```rust,no_run
use axum::{
    extract::Request,
    http::{header, StatusCode},
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use tokio::task_local;

#[derive(Clone)]
struct CurrentUser {
    name: String,
}
task_local! {
    pub static USER: CurrentUser;
}

async fn auth(req: Request, next: Next) -> Result<Response, StatusCode> {
    let auth_header = req
        .headers()
        .get(header::AUTHORIZATION)
        .and_then(|header| header.to_str().ok())
        .ok_or(StatusCode::UNAUTHORIZED)?;
    if let Some(current_user) = authorize_current_user(auth_header).await {
        // State is setup here in the middleware
        Ok(USER.scope(current_user, next.run(req)).await)
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}
async fn authorize_current_user(auth_token: &str) -> Option<CurrentUser> {
    Some(CurrentUser {
        name: auth_token.to_string(),
    })
}

struct UserResponse;

impl IntoResponse for UserResponse {
    fn into_response(self) -> Response {
        // State is accessed here in the IntoResponse implementation
        let current_user = USER.with(|u| u.clone());
        (StatusCode::OK, current_user.name).into_response()
    }
}

async fn handler() -> UserResponse {
    UserResponse
}

let app: Router = Router::new()
    .route("/", get(handler))
    .route_layer(middleware::from_fn(auth));
```

The main downside to this approach is that it only works when the async executor being used
has the concept of task-local variables. The example above uses
[tokio's `task_local` macro](https://docs.rs/tokio/1/tokio/macro.task_local.html).
smol does not yet offer equivalent functionality at the time of writing (see
[this GitHub issue](https://github.com/smol-rs/async-executor/issues/139)).

### axum › Building integrations for axum

Libraries authors that want to provide [`FromRequest`], [`FromRequestParts`], or
[`IntoResponse`] implementations should depend on the [`axum-core`] crate, instead of `axum` if
possible. [`axum-core`] contains core types and traits and is less likely to receive breaking
changes.

### axum › Required dependencies

To use axum there are a few dependencies you have to pull in as well:

```toml
[dependencies]
axum = "<latest-version>"
tokio = { version = "<latest-version>", features = ["full"] }
tower = "<latest-version>"
```

The `"full"` feature for tokio isn't necessary but it's the easiest way to get started.

Tower isn't strictly necessary either but helpful for testing. See the
testing example in the repo to learn more about testing axum apps.

### axum › Examples

The axum repo contains [a number of examples][examples] that show how to put all the
pieces together.

### axum › Feature flags

axum uses a set of [feature flags] to reduce the amount of compiled and
optional dependencies.

The following optional features are available:

Name | Description | Default?
---|---|---
`http1` | Enables hyper's `http1` feature | <span role="img" aria-label="Default feature">✔</span>
`http2` | Enables hyper's `http2` feature |
`json` | Enables the [`Json`] type and some similar convenience functionality | <span role="img" aria-label="Default feature">✔</span>
`macros` | Enables optional utility macros |
`matched-path` | Enables capturing of every request's router path and the [`MatchedPath`] extractor | <span role="img" aria-label="Default feature">✔</span>
`multipart` | Enables parsing `multipart/form-data` requests with [`Multipart`] |
`original-uri` | Enables capturing of every request's original URI and the [`OriginalUri`] extractor | <span role="img" aria-label="Default feature">✔</span>
`tokio` | Enables `tokio` as a dependency and `axum::serve`, `SSE` and `extract::connect_info` types. | <span role="img" aria-label="Default feature">✔</span>
`tower-log` | Enables `tower`'s `log` feature | <span role="img" aria-label="Default feature">✔</span>
`tracing` | Log rejections from built-in extractors | <span role="img" aria-label="Default feature">✔</span>
`ws` | Enables WebSockets support via [`extract::ws`] |
`form` | Enables the `Form` extractor | <span role="img" aria-label="Default feature">✔</span>
`query` | Enables the `Query` extractor | <span role="img" aria-label="Default feature">✔</span>

[`MatchedPath`]: crate::extract::MatchedPath
[`Multipart`]: crate::extract::Multipart
[`OriginalUri`]: crate::extract::OriginalUri
[`tower`]: https://crates.io/crates/tower
[`tower-http`]: https://crates.io/crates/tower-http
[`tokio`]: http://crates.io/crates/tokio
[`hyper`]: http://crates.io/crates/hyper
[`tonic`]: http://crates.io/crates/tonic
[feature flags]: https://doc.rust-lang.org/cargo/reference/features.html#the-features-section
[`IntoResponse`]: crate::response::IntoResponse
[`Timeout`]: tower::timeout::Timeout
[examples]: https://github.com/tokio-rs/axum/tree/main/examples
[`Router::merge`]: crate::routing::Router::merge
[`Service`]: tower::Service
[`Service::poll_ready`]: tower::Service::poll_ready
[`Service`'s]: tower::Service
[`tower::Service`]: tower::Service
[tower-guides]: https://github.com/tower-rs/tower/tree/master/guides
[`Uuid`]: https://docs.rs/uuid/latest/uuid/
[`FromRequest`]: crate::extract::FromRequest
[`FromRequestParts`]: crate::extract::FromRequestParts
[`HeaderMap`]: http::header::HeaderMap
[`Request`]: http::Request
[customize-extractor-error]: https://github.com/tokio-rs/axum/blob/main/examples/customize-extractor-error/src/main.rs
[axum-macros]: https://docs.rs/axum-macros
[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html
[`Handler`]: crate::handler::Handler
[`Infallible`]: std::convert::Infallible
[load shed]: tower::load_shed
[`axum-core`]: http://crates.io/crates/axum-core
[`State`]: crate::extract::State
[`FromRef`]: crate::extract::FromRef
[`Router::with_state`]: crate::routing::Router::with_state

## axum::body (module)

HTTP body utilities.

## axum::error_handling (module)

Error handling model and utilities

### axum::error_handling (module) › axum's error handling model

axum is based on [`tower::Service`] which bundles errors through its associated
`Error` type. If you have a [`Service`] that produces an error and that error
makes it all the way up to hyper, the connection will be terminated _without_
sending a response. This is generally not desirable so axum makes sure you
always produce a response by relying on the type system.

axum does this by requiring all services have [`Infallible`] as their error
type. `Infallible` is the error type for errors that can never happen.

This means if you define a handler like:

```rust
use axum::http::StatusCode;

async fn handler() -> Result<String, StatusCode> {
    # todo!()
    // ...
}
```

While it looks like it might fail with a `StatusCode` this actually isn't an
"error". If this handler returns `Err(some_status_code)` that will still be
converted into a [`Response`] and sent back to the client. This is done
through `StatusCode`'s [`IntoResponse`] implementation.

It doesn't matter whether you return `Err(StatusCode::NOT_FOUND)` or
`Err(StatusCode::INTERNAL_SERVER_ERROR)`. These are not considered errors in
axum.

Instead of a direct `StatusCode`, it makes sense to use intermediate error type
that can ultimately be converted to `Response`. This allows using `?` operator
in handlers. See those examples:

* [`anyhow-error-response`][anyhow] for generic boxed errors
* [`error-handling`][error-handling] for application-specific detailed errors

[anyhow]: https://github.com/tokio-rs/axum/blob/main/examples/anyhow-error-response/src/main.rs
[error-handling]: https://github.com/tokio-rs/axum/blob/main/examples/error-handling/src/main.rs

This also applies to extractors. If an extractor doesn't match the request the
request will be rejected and a response will be returned without calling your
handler. See [`extract`](crate::extract) to learn more about handling extractor
failures.

### axum::error_handling (module) › Routing to fallible services

You generally don't have to think about errors if you're only using async
functions as handlers. However if you're embedding general `Service`s or
applying middleware, which might produce errors you have to tell axum how to
convert those errors into responses.

```rust
use axum::{
    Router,
    body::Body,
    http::{Request, Response, StatusCode},
    error_handling::HandleError,
};

async fn thing_that_might_fail() -> Result<(), anyhow::Error> {
    # Ok(())
    // ...
}

// this service might fail with `anyhow::Error`
let some_fallible_service = tower::service_fn(|_req| async {
    thing_that_might_fail().await?;
    Ok::<_, anyhow::Error>(Response::new(Body::empty()))
});

let app = Router::new().route_service(
    "/",
    // we cannot route to `some_fallible_service` directly since it might fail.
    // we have to use `handle_error` which converts its errors into responses
    // and changes its error type from `anyhow::Error` to `Infallible`.
    HandleError::new(some_fallible_service, handle_anyhow_error),
);

// handle errors by converting them into something that implements
// `IntoResponse`
async fn handle_anyhow_error(err: anyhow::Error) -> (StatusCode, String) {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        format!("Something went wrong: {err}"),
    )
}
# let _: Router = app;
```

### axum::error_handling (module) › Applying fallible middleware

Similarly axum requires you to handle errors from middleware. That is done with
[`HandleErrorLayer`]:

```rust
use axum::{
    Router,
    BoxError,
    routing::get,
    http::StatusCode,
    error_handling::HandleErrorLayer,
};
use std::time::Duration;
use tower::ServiceBuilder;

let app = Router::new()
    .route("/", get(|| async {}))
    .layer(
        ServiceBuilder::new()
            // `timeout` will produce an error if the handler takes
            // too long so we must handle those
            .layer(HandleErrorLayer::new(handle_timeout_error))
            .timeout(Duration::from_secs(30))
    );

async fn handle_timeout_error(err: BoxError) -> (StatusCode, String) {
    if err.is::<tower::timeout::error::Elapsed>() {
        (
            StatusCode::REQUEST_TIMEOUT,
            "Request took too long".to_string(),
        )
    } else {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Unhandled internal error: {err}"),
        )
    }
}
# let _: Router = app;
```

### axum::error_handling (module) › Running extractors for error handling

`HandleErrorLayer` also supports running extractors:

```rust
use axum::{
    Router,
    BoxError,
    routing::get,
    http::{StatusCode, Method, Uri},
    error_handling::HandleErrorLayer,
};
use std::time::Duration;
use tower::ServiceBuilder;

let app = Router::new()
    .route("/", get(|| async {}))
    .layer(
        ServiceBuilder::new()
            // `timeout` will produce an error if the handler takes
            // too long so we must handle those
            .layer(HandleErrorLayer::new(handle_timeout_error))
            .timeout(Duration::from_secs(30))
    );

async fn handle_timeout_error(
    // `Method` and `Uri` are extractors so they can be used here
    method: Method,
    uri: Uri,
    // the last argument must be the error itself
    err: BoxError,
) -> (StatusCode, String) {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        format!("`{method} {uri}` failed with {err}"),
    )
}
# let _: Router = app;
```

[`tower::Service`]: `tower::Service`
[`Infallible`]: std::convert::Infallible
[`Response`]: crate::response::Response
[`IntoResponse`]: crate::response::IntoResponse

## axum::error_handling::future (module)

Future types.

## axum::extract (module)

Types and traits for extracting data from requests.

### axum::extract (module) › Intro

A handler function is an async function that takes any number of
"extractors" as arguments. An extractor is a type that implements
[`FromRequest`] or [`FromRequestParts`].

For example, [`Json`] is an extractor that consumes the request body and
deserializes it as JSON into some target type:

```rust,no_run
use axum::{
    extract::Json,
    routing::post,
    handler::Handler,
    Router,
};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}

async fn create_user(Json(payload): Json<CreateUser>) {
    // ...
}

let app = Router::new().route("/users", post(create_user));
# let _: Router = app;
```

### axum::extract (module) › Common extractors

Some commonly used extractors are:

```rust,no_run
use axum::{
    extract::{Request, Json, Path, Extension, Query},
    routing::post,
    http::header::HeaderMap,
    body::{Bytes, Body},
    Router,
};
use serde_json::Value;
use std::collections::HashMap;

// `Path` gives you the path parameters and deserializes them. See its docs for
// more details
async fn path(Path(user_id): Path<u32>) {}

// `Query` gives you the query parameters and deserializes them.
async fn query(Query(params): Query<HashMap<String, String>>) {}

// `HeaderMap` gives you all the headers
async fn headers(headers: HeaderMap) {}

// `String` consumes the request body and ensures it is valid utf-8
async fn string(body: String) {}

// `Bytes` gives you the raw request body
async fn bytes(body: Bytes) {}

// We've already seen `Json` for parsing the request body as json
async fn json(Json(payload): Json<Value>) {}

// `Request` gives you the whole request for maximum control
async fn request(request: Request) {}

// `Extension` extracts data from "request extensions"
// This is commonly used to share state with handlers
async fn extension(Extension(state): Extension<State>) {}

#[derive(Clone)]
struct State { /* ... */ }

let app = Router::new()
    .route("/path/{user_id}", post(path))
    .route("/query", post(query))
    .route("/string", post(string))
    .route("/bytes", post(bytes))
    .route("/json", post(json))
    .route("/request", post(request))
    .route("/extension", post(extension));
# let _: Router = app;
```

### axum::extract (module) › Applying multiple extractors

You can also apply multiple extractors:

```rust,no_run
use axum::{
    extract::{Path, Query},
    routing::get,
    Router,
};
use uuid::Uuid;
use serde::Deserialize;

let app = Router::new().route("/users/{id}/things", get(get_user_things));

#[derive(Deserialize)]
struct Pagination {
    page: usize,
    per_page: usize,
}

async fn get_user_things(
    Path(user_id): Path<Uuid>,
    Query(pagination): Query<Pagination>,
) {
    // ...
}
# let _: Router = app;
```

### axum::extract (module) › The order of extractors

Extractors always run in the order of the function parameters that is from
left to right.

The request body is an asynchronous stream that can only be consumed once.
Therefore you can only have one extractor that consumes the request body. axum
enforces this by requiring such extractors to be the _last_ argument your
handler takes.

For example

```rust
use axum::{extract::State, http::{Method, HeaderMap}};
#
# #[derive(Clone)]
# struct AppState {
# }

async fn handler(
    // `Method` and `HeaderMap` don't consume the request body so they can
    // put anywhere in the argument list (but before `body`)
    method: Method,
    headers: HeaderMap,
    // `State` is also an extractor so it needs to be before `body`
    State(state): State<AppState>,
    // `String` consumes the request body and thus must be the last extractor
    body: String,
) {
    // ...
}
#
# let _: axum::routing::MethodRouter<AppState> = axum::routing::get(handler);
```

We get a compile error if `String` isn't the last extractor:

```rust,compile_fail
use axum::http::Method;

async fn handler(
    // this doesn't work since `String` must be the last argument
    body: String,
    method: Method,
) {
    // ...
}
#
# let _: axum::routing::MethodRouter = axum::routing::get(handler);
```

This also means you cannot consume the request body twice:

```rust,compile_fail
use axum::Json;
use serde::Deserialize;

#[derive(Deserialize)]
struct Payload {}

async fn handler(
    // `String` and `Json` both consume the request body
    // so they cannot both be used
    string_body: String,
    json_body: Json<Payload>,
) {
    // ...
}
#
# let _: axum::routing::MethodRouter = axum::routing::get(handler);
```

axum enforces this by requiring the last extractor implements [`FromRequest`]
and all others implement [`FromRequestParts`].

### axum::extract (module) › Handling extractor rejections

If you want to handle the case of an extractor failing within a specific
handler, you can wrap it in `Result`, with the error being the rejection type
of the extractor:

```rust,no_run
use axum::{
    extract::{Json, rejection::JsonRejection},
    routing::post,
    Router,
};
use serde_json::Value;

async fn create_user(payload: Result<Json<Value>, JsonRejection>) {
    match payload {
        Ok(payload) => {
            // We got a valid JSON payload
        }
        Err(JsonRejection::MissingJsonContentType(_)) => {
            // Request didn't have `Content-Type: application/json`
            // header
        }
        Err(JsonRejection::JsonDataError(_)) => {
            // Couldn't deserialize the body into the target type
        }
        Err(JsonRejection::JsonSyntaxError(_)) => {
            // Syntax error in the body
        }
        Err(JsonRejection::BytesRejection(_)) => {
            // Failed to extract the request body
        }
        Err(_) => {
            // `JsonRejection` is marked `#[non_exhaustive]` so match must
            // include a catch-all case.
        }
    }
}

let app = Router::new().route("/users", post(create_user));
# let _: Router = app;
```

### axum::extract (module) › Optional extractors

Some extractors implement [`OptionalFromRequestParts`] in addition to
[`FromRequestParts`], or [`OptionalFromRequest`] in addition to [`FromRequest`].

These extractors can be used inside of `Option`. It depends on the particular
`OptionalFromRequestParts` or `OptionalFromRequest` implementation what this
does: For example for `TypedHeader` from axum-extra, you get `None` if the
header you're trying to extract is not part of the request, but if the header
is present and fails to parse, the request is rejected.

```rust,no_run
use axum::{routing::post, Router};
use axum_extra::{headers::UserAgent, TypedHeader};
use serde_json::Value;

async fn foo(user_agent: Option<TypedHeader<UserAgent>>) {
    if let Some(TypedHeader(user_agent)) = user_agent {
        // The client sent a user agent
    } else {
        // No user agent header
    }
}

let app = Router::new().route("/foo", post(foo));
# let _: Router = app;
```

### axum::extract (module) › Customizing extractor responses

If an extractor fails it will return a response with the error and your
handler will not be called. To customize the error response you have two
options:

1. Use `Result<T, T::Rejection>` as your extractor like shown in
   ["Handling extractor rejections"](#handling-extractor-rejections).
   This works well if you're only using the extractor in a single handler.
2. Create your own extractor that in its [`FromRequest`] implementation calls
   one of axum's built in extractors but returns a different response for
   rejections. See the [customize-extractor-error] example for more details.

### axum::extract (module) › Accessing inner errors

axum's built-in extractors don't directly expose the inner error. This gives us
more flexibility and allows us to change internal implementations without
breaking the public API.

For example that means while [`Json`] is implemented using [`serde_json`] it
doesn't directly expose the [`serde_json::Error`] that's contained in
[`JsonRejection::JsonDataError`]. However it is still possible to access via
methods from [`std::error::Error`]:

```rust
use std::error::Error;
use axum::{
    extract::{Json, rejection::JsonRejection},
    response::IntoResponse,
    http::StatusCode,
};
use serde_json::{json, Value};

async fn handler(
    result: Result<Json<Value>, JsonRejection>,
) -> Result<Json<Value>, (StatusCode, String)> {
    match result {
        // if the client sent valid JSON then we're good
        Ok(Json(payload)) => Ok(Json(json!({ "payload": payload }))),

        Err(err) => match err {
            JsonRejection::JsonDataError(err) => {
                Err(serde_json_error_response(err))
            }
            JsonRejection::JsonSyntaxError(err) => {
                Err(serde_json_error_response(err))
            }
            // handle other rejections from the `Json` extractor
            JsonRejection::MissingJsonContentType(_) => Err((
                StatusCode::BAD_REQUEST,
                "Missing `Content-Type: application/json` header".to_string(),
            )),
            JsonRejection::BytesRejection(_) => Err((
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to buffer request body".to_string(),
            )),
            // we must provide a catch-all case since `JsonRejection` is marked
            // `#[non_exhaustive]`
            _ => Err((
                StatusCode::INTERNAL_SERVER_ERROR,
                "Unknown error".to_string(),
            )),
        },
    }
}

// attempt to extract the inner `serde_path_to_error::Error<serde_json::Error>`,
// if that succeeds we can provide a more specific error.
//
// `Json` uses `serde_path_to_error` so the error will be wrapped in `serde_path_to_error::Error`.
fn serde_json_error_response<E>(err: E) -> (StatusCode, String)
where
    E: Error + 'static,
{
    if let Some(err) = find_error_source::<serde_path_to_error::Error<serde_json::Error>>(&err) {
        let serde_json_err = err.inner();
        (
            StatusCode::BAD_REQUEST,
            format!(
                "Invalid JSON at line {} column {}",
                serde_json_err.line(),
                serde_json_err.column()
            ),
        )
    } else {
        (StatusCode::BAD_REQUEST, "Unknown error".to_string())
    }
}

// attempt to downcast `err` into a `T` and if that fails recursively try and
// downcast `err`'s source
fn find_error_source<'a, T>(err: &'a (dyn Error + 'static)) -> Option<&'a T>
where
    T: Error + 'static,
{
    if let Some(err) = err.downcast_ref::<T>() {
        Some(err)
    } else if let Some(source) = err.source() {
        find_error_source(source)
    } else {
        None
    }
}
#
# #[tokio::main]
# async fn main() {
#     use axum::extract::FromRequest;
#
#     let req = axum::http::Request::builder()
#         .header("content-type", "application/json")
#         .body(axum::body::Body::from("{"))
#         .unwrap();
#
#     let err = match Json::<serde_json::Value>::from_request(req, &()).await.unwrap_err() {
#         JsonRejection::JsonSyntaxError(err) => err,
#         _ => panic!(),
#     };
#
#     let (_, body) = serde_json_error_response(err);
#     assert_eq!(body, "Invalid JSON at line 1 column 1");
# }
```

Note that while this approach works it might break in the future if axum changes
its implementation to use a different error type internally. Such changes might
happen without major breaking versions.

### axum::extract (module) › Defining custom extractors

You can also define your own extractors by implementing either
[`FromRequestParts`] or [`FromRequest`].

### axum::extract (module) › Implementing `FromRequestParts`

Implement `FromRequestParts` if your extractor doesn't need access to the
request body:

```rust,no_run
use axum::{
    extract::FromRequestParts,
    routing::get,
    Router,
    http::{
        StatusCode,
        header::{HeaderValue, USER_AGENT},
        request::Parts,
    },
};

struct ExtractUserAgent(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) {
    // ...
}

let app = Router::new().route("/foo", get(handler));
# let _: Router = app;
```

### axum::extract (module) › Implementing `FromRequest`

If your extractor needs to consume the request body you must implement [`FromRequest`]

```rust,no_run
use axum::{
    extract::{Request, FromRequest},
    response::{Response, IntoResponse},
    body::{Bytes, Body},
    routing::get,
    Router,
    http::{
        StatusCode,
        header::{HeaderValue, USER_AGENT},
    },
};

struct ValidatedBody(Bytes);

impl<S> FromRequest<S> for ValidatedBody
where
    Bytes: FromRequest<S>,
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let body = Bytes::from_request(req, state)
            .await
            .map_err(IntoResponse::into_response)?;

        // do validation...

        Ok(Self(body))
    }
}

async fn handler(ValidatedBody(body): ValidatedBody) {
    // ...
}

let app = Router::new().route("/foo", get(handler));
# let _: Router = app;
```

### axum::extract (module) › Cannot implement both `FromRequest` and `FromRequestParts`

Note that you will make your extractor unusable by implementing both
`FromRequest` and `FromRequestParts` directly for the same type, unless it is
wrapping another extractor:

```rust,compile_fail
use axum::{
    Router,
    routing::get,
    extract::{FromRequest, Request, FromRequestParts},
    http::request::Parts,
    body::Body,
};
use std::convert::Infallible;

// Some extractor that doesn't wrap another extractor
struct MyExtractor;

// `MyExtractor` implements both `FromRequest`
impl<S> FromRequest<S> for MyExtractor
where
    S: Send + Sync,
{
    type Rejection = Infallible;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // ...
        # todo!()
    }
}

// and `FromRequestParts`
impl<S> FromRequestParts<S> for MyExtractor
where
    S: Send + Sync,
{
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        // ...
        # todo!()
    }
}

let app = Router::new().route(
    "/",
    // This fails when we go to actually use `MyExtractor` in a handler function.
    // This is due to a limit in Rust's type system.
    //
    // The workaround is to implement either `FromRequest` or `FromRequestParts`
    // but not both, if your extractor doesn't wrap another extractor.
    //
    // See "Wrapping extractors" for how to wrap other extractors.
    get(|_: MyExtractor| async {}),
);
# let _: Router = app;
```

### axum::extract (module) › Accessing other extractors in `FromRequest` or `FromRequestParts` implementations

When defining custom extractors you often need to access another extractor
in your implementation.

```rust
use axum::{
    extract::{Extension, FromRequestParts},
    http::{StatusCode, HeaderMap, request::Parts},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

#[derive(Clone)]
struct State {
    // ...
}

struct AuthenticatedUser {
    // ...
}

impl<S> FromRequestParts<S> for AuthenticatedUser
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        // You can either call them directly...
        let headers = HeaderMap::from_request_parts(parts, state)
            .await
            .map_err(|err| match err {})?;

        // ... or use `extract` / `extract_with_state` from `RequestExt` / `RequestPartsExt`
        use axum::RequestPartsExt;
        let Extension(state) = parts.extract::<Extension<State>>()
            .await
            .map_err(|err| err.into_response())?;

        unimplemented!("actually perform the authorization")
    }
}

async fn handler(user: AuthenticatedUser) {
    // ...
}

let state = State { /* ... */ };

let app = Router::new().route("/", get(handler)).layer(Extension(state));
# let _: Router = app;
```

### axum::extract (module) › Request body limits

For security reasons, [`Bytes`] will, by default, not accept bodies larger than
2MB. This also applies to extractors that uses [`Bytes`] internally such as
`String`, [`Json`], and [`Form`].

For more details, including how to disable this limit, see [`DefaultBodyLimit`].

### axum::extract (module) › Wrapping extractors

If you want to write an extractor that generically wraps another extractor
(that may or may not consume the request body) you should implement both
[`FromRequest`] and [`FromRequestParts`]:

```rust
use axum::{
    Router,
    body::Body,
    routing::get,
    extract::{Request, FromRequest, FromRequestParts},
    http::{HeaderMap, request::Parts},
};
use std::time::{Instant, Duration};

// an extractor that wraps another and measures how long time it takes to run
struct Timing<E> {
    extractor: E,
    duration: Duration,
}

// we must implement both `FromRequestParts`
impl<S, T> FromRequestParts<S> for Timing<T>
where
    S: Send + Sync,
    T: FromRequestParts<S>,
{
    type Rejection = T::Rejection;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let start = Instant::now();
        let extractor = T::from_request_parts(parts, state).await?;
        let duration = start.elapsed();
        Ok(Timing {
            extractor,
            duration,
        })
    }
}

// and `FromRequest`
impl<S, T> FromRequest<S> for Timing<T>
where
    S: Send + Sync,
    T: FromRequest<S>,
{
    type Rejection = T::Rejection;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let start = Instant::now();
        let extractor = T::from_request(req, state).await?;
        let duration = start.elapsed();
        Ok(Timing {
            extractor,
            duration,
        })
    }
}

async fn handler(
    // this uses the `FromRequestParts` impl
    _: Timing<HeaderMap>,
    // this uses the `FromRequest` impl
    _: Timing<String>,
) {}
# let _: axum::routing::MethodRouter = axum::routing::get(handler);
```

### axum::extract (module) › Logging rejections

All built-in extractors will log rejections for easier debugging. To see the
logs, enable the `tracing` feature for axum (enabled by default) and the
`axum::rejection=trace` tracing target, for example with
`RUST_LOG=info,axum::rejection=trace cargo run`.

[axum-extra]: https://docs.rs/axum-extra/latest/axum_extra/extract/index.html
[`body::Body`]: crate::body::Body
[`Bytes`]: crate::body::Bytes
[customize-extractor-error]: https://github.com/tokio-rs/axum/blob/main/examples/customize-extractor-error/src/main.rs
[`HeaderMap`]: https://docs.rs/http/latest/http/header/struct.HeaderMap.html
[`Request`]: https://docs.rs/http/latest/http/struct.Request.html
[`JsonRejection::JsonDataError`]: rejection::JsonRejection::JsonDataError

## axum::extract::connect_info (module)

Extractor for getting connection information from a client.

See [`Router::into_make_service_with_connect_info`] for more details.

[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info

## axum::extract::multipart (module)

Extractor that parses `multipart/form-data` requests commonly used with file uploads.

See [`Multipart`] for more details.

## axum::extract::path (module)

Extractor that will get captures from the URL and parse them using
[`serde`].

## axum::extract::rejection (module)

Rejection response types.

## axum::extract::ws (module)

Handle WebSocket connections.

### axum::extract::ws (module) › Example

```
use axum::{
    extract::ws::{WebSocketUpgrade, WebSocket},
    routing::any,
    response::{IntoResponse, Response},
    Router,
};

let app = Router::new().route("/ws", any(handler));

async fn handler(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let msg = if let Ok(msg) = msg {
            msg
        } else {
            // client disconnected
            return;
        };

        if socket.send(msg).await.is_err() {
            // client disconnected
            return;
        }
    }
}
# let _: Router = app;
```

### axum::extract::ws (module) › Passing data and/or state to an `on_upgrade` callback

```
use axum::{
    extract::{ws::{WebSocketUpgrade, WebSocket}, State},
    response::Response,
    routing::any,
    Router,
};

#[derive(Clone)]
struct AppState {
    // ...
}

async fn handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> Response {
    ws.on_upgrade(|socket| handle_socket(socket, state))
}

async fn handle_socket(socket: WebSocket, state: AppState) {
    // ...
}

let app = Router::new()
    .route("/ws", any(handler))
    .with_state(AppState { /* ... */ });
# let _: Router = app;
```

### axum::extract::ws (module) › Read and write concurrently

If you need to read and write concurrently from a [`WebSocket`] you can use
[`StreamExt::split`]:

```rust,no_run
use axum::{Error, extract::ws::{WebSocket, Message}};
use futures_util::{sink::SinkExt, stream::{StreamExt, SplitSink, SplitStream}};

async fn handle_socket(mut socket: WebSocket) {
    let (mut sender, mut receiver) = socket.split();

    tokio::spawn(write(sender));
    tokio::spawn(read(receiver));
}

async fn read(receiver: SplitStream<WebSocket>) {
    // ...
}

async fn write(sender: SplitSink<WebSocket, Message>) {
    // ...
}
```

[`StreamExt::split`]: https://docs.rs/futures/0.3.17/futures/stream/trait.StreamExt.html#method.split

## axum::extract::ws::close_code (module)

Constants for [`CloseCode`]s.

[`CloseCode`]: super::CloseCode

## axum::extract::ws::rejection (module)

WebSocket specific rejections.

## axum::handler (module)

Async functions that can be used to handle requests.

In axum a "handler" is an async function that accepts zero or more
["extractors"](crate::extract) as arguments and returns something that
can be converted [into a response](crate::response).

Handlers are where your application logic lives and axum applications are built
by routing between handlers.

[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html

Some examples of handlers:

```rust
use axum::{body::Bytes, http::StatusCode};

// Handler that immediately returns an empty `200 OK` response.
async fn unit_handler() {}

// Handler that immediately returns a `200 OK` response with a plain text
// body.
async fn string_handler() -> String {
    "Hello, World!".to_string()
}

// Handler that buffers the request body and returns it.
//
// This works because `Bytes` implements `FromRequest`
// and therefore can be used as an extractor.
//
// `String` and `StatusCode` both implement `IntoResponse` and
// therefore `Result<String, StatusCode>` also implements `IntoResponse`
async fn echo(body: Bytes) -> Result<String, StatusCode> {
    if let Ok(string) = String::from_utf8(body.to_vec()) {
        Ok(string)
    } else {
        Err(StatusCode::BAD_REQUEST)
    }
}
```

Instead of a direct `StatusCode`, it makes sense to use intermediate error type
that can ultimately be converted to `Response`. This allows using `?` operator
in handlers. See those examples:

* [`anyhow-error-response`][anyhow] for generic boxed errors
* [`error-handling`][error-handling] for application-specific detailed errors

[anyhow]: https://github.com/tokio-rs/axum/blob/main/examples/anyhow-error-response/src/main.rs
[error-handling]: https://github.com/tokio-rs/axum/blob/main/examples/error-handling/src/main.rs

### axum::handler (module) › 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:

- Are `async fn`s.
- Take no more than 16 arguments that all implement `Send`.
  - All except the last argument implement [`FromRequestParts`].
  - The last argument implements [`FromRequest`].
- Returns something that implements [`IntoResponse`].
- If a closure is used it must implement `Clone + Send` and be
`'static`.
- Returns a future that is `Send`. The most common way to accidentally make a
future `!Send` is to hold a `!Send` type across an await.

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:

```not_rust
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.

[axum-macros]: https://docs.rs/axum-macros
[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html

## axum::handler::future (module)

Handler future types.

## axum::middleware (module)

Utilities for writing middleware

### axum::middleware (module) › Intro

axum is unique in that it doesn't have its own bespoke middleware system and
instead integrates with [`tower`]. This means the ecosystem of [`tower`] and
[`tower-http`] middleware all work with axum.

While it's not necessary to fully understand tower to write or use middleware
with axum, having at least a basic understanding of tower's concepts is
recommended. See [tower's guides][tower-guides] for a general introduction.
Reading the documentation for [`tower::ServiceBuilder`] is also recommended.

### axum::middleware (module) › Applying middleware

axum allows you to add middleware just about anywhere

- To entire routers with [`Router::layer`] and [`Router::route_layer`].
- To method routers with [`MethodRouter::layer`] and [`MethodRouter::route_layer`].
- To individual handlers with [`Handler::layer`].

### axum::middleware (module) › Applying multiple middleware

It's recommended to use [`tower::ServiceBuilder`] to apply multiple middleware at
once, instead of calling `layer` (or `route_layer`) repeatedly:

```rust
use axum::{
    routing::get,
    Extension,
    Router,
};
use tower_http::{trace::TraceLayer};
use tower::ServiceBuilder;

async fn handler() {}

#[derive(Clone)]
struct State {}

let app = Router::new()
    .route("/", get(handler))
    .layer(
        ServiceBuilder::new()
            .layer(TraceLayer::new_for_http())
            .layer(Extension(State {}))
    );
# let _: Router = app;
```

### axum::middleware (module) › Commonly used middleware

Some commonly used middleware are:

- [`TraceLayer`](tower_http::trace) for high level tracing/logging.
- [`CorsLayer`](tower_http::cors) for handling CORS.
- [`CompressionLayer`](tower_http::compression) for automatic compression of responses.
- [`RequestIdLayer`](tower_http::request_id) and
  [`PropagateRequestIdLayer`](tower_http::request_id) set and propagate request
  ids.
- [`TimeoutLayer`](tower_http::timeout::TimeoutLayer) for timeouts.

### axum::middleware (module) › Ordering

When you add middleware with [`Router::layer`] (or similar) all previously added
routes will be wrapped in the middleware. Generally speaking, this results in
middleware being executed from bottom to top.

So if you do this:

```rust
use axum::{routing::get, Router};

async fn handler() {}

# let layer_one = axum::Extension(());
# let layer_two = axum::Extension(());
# let layer_three = axum::Extension(());
#
let app = Router::new()
    .route("/", get(handler))
    .layer(layer_one)
    .layer(layer_two)
    .layer(layer_three);
# let _: Router = app;
```

Think of the middleware as being layered like an onion where each new layer
wraps all previous layers:

```not_rust
        requests
           |
           v
+----- layer_three -----+
| +---- layer_two ----+ |
| | +-- layer_one --+ | |
| | |               | | |
| | |    handler    | | |
| | |               | | |
| | +-- layer_one --+ | |
| +---- layer_two ----+ |
+----- layer_three -----+
           |
           v
        responses
```

That is:

- First `layer_three` receives the request
- It then does its thing and passes the request onto `layer_two`
- Which passes the request onto `layer_one`
- Which passes the request onto `handler` where a response is produced
- That response is then passed to `layer_one`
- Then to `layer_two`
- And finally to `layer_three` where it's returned out of your app

It's a little more complicated in practice because any middleware is free to
return early and not call the next layer, for example if a request cannot be
authorized, but it's a useful mental model to have.

As previously mentioned it's recommended to add multiple middleware using
`tower::ServiceBuilder`, however this impacts ordering:

```rust
use tower::ServiceBuilder;
use axum::{routing::get, Router};

async fn handler() {}

# let layer_one = axum::Extension(());
# let layer_two = axum::Extension(());
# let layer_three = axum::Extension(());
#
let app = Router::new()
    .route("/", get(handler))
    .layer(
        ServiceBuilder::new()
            .layer(layer_one)
            .layer(layer_two)
            .layer(layer_three),
    );
# let _: Router = app;
```

`ServiceBuilder` works by composing all layers into one such that they run top
to bottom. So with the previous code `layer_one` would receive the request
first, then `layer_two`, then `layer_three`, then `handler`, and then the
response would bubble back up through `layer_three`, then `layer_two`, and
finally `layer_one`.

Executing middleware top to bottom is generally easier to understand and follow
mentally which is one of the reasons `ServiceBuilder` is recommended.

### axum::middleware (module) › Writing middleware

axum offers many ways of writing middleware, at different levels of abstraction
and with different pros and cons.

### axum::middleware (module) › `axum::middleware::from_fn`

Use [`axum::middleware::from_fn`] to write your middleware when:

- You're not comfortable with implementing your own futures and would rather use
  the familiar `async`/`await` syntax.
- You don't intend to publish your middleware as a crate for others to use.
  Middleware written like this are only compatible with axum.

### axum::middleware (module) › `axum::middleware::from_extractor`

Use [`axum::middleware::from_extractor`] to write your middleware when:

- You have a type that you sometimes want to use as an extractor and sometimes
  as a middleware. If you only need your type as a middleware prefer
  [`middleware::from_fn`].

### axum::middleware (module) › tower's combinators

tower has several utility combinators that can be used to perform simple
modifications to requests or responses. The most commonly used ones are

- [`ServiceBuilder::map_request`]
- [`ServiceBuilder::map_response`]
- [`ServiceBuilder::then`]
- [`ServiceBuilder::and_then`]

You should use these when

- You want to perform a small ad hoc operation, such as adding a header.
- You don't intend to publish your middleware as a crate for others to use.

### axum::middleware (module) › `tower::Service` and `Pin<Box<dyn Future>>`

For maximum control (and a more low level API) you can write your own middleware
by implementing [`tower::Service`]:

Use [`tower::Service`] with `Pin<Box<dyn Future>>` to write your middleware when:

- Your middleware needs to be configurable for example via builder methods on
  your [`tower::Layer`] such as [`tower_http::trace::TraceLayer`].
- You do intend to publish your middleware as a crate for others to use.
- You're not comfortable with implementing your own futures.

A decent template for such a middleware could be:

```rust
use axum::{
    response::Response,
    body::Body,
    extract::Request,
};
use futures_util::future::BoxFuture;
use tower::{Service, Layer};
use std::task::{Context, Poll};

#[derive(Clone)]
struct MyLayer;

impl<S> Layer<S> for MyLayer {
    type Service = MyMiddleware<S>;

    fn layer(&self, inner: S) -> Self::Service {
        MyMiddleware { inner }
    }
}

#[derive(Clone)]
struct MyMiddleware<S> {
    inner: S,
}

impl<S> Service<Request> for MyMiddleware<S>
where
    S: Service<Request, Response = Response> + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    // `BoxFuture` is a type alias for `Pin<Box<dyn Future + Send + 'a>>`
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request) -> Self::Future {
        let future = self.inner.call(request);
        Box::pin(async move {
            let response: Response = future.await?;
            Ok(response)
        })
    }
}
```

Note that your error type being defined as `S::Error` means that your middleware typically _returns no errors_. As a principle always try to return a response and try not to bail out with a custom error type. For example, if a 3rd party library you are using inside your new middleware returns its own specialized error type, try to convert it to some reasonable response and return `Ok` with that response.

If you choose to implement a custom error type such as `type Error = BoxError` (a boxed opaque error), or any other error type that is not `Infallible`, you must use a `HandleErrorLayer`, here is an example using a `ServiceBuilder`:

```ignore
ServiceBuilder::new()
        .layer(HandleErrorLayer::new(|_: BoxError| async {
            // because axum uses infallible errors, you must handle your custom error type from your middleware here
            StatusCode::BAD_REQUEST
        }))
        .layer(
             // <your actual layer which DOES return an error>
        );
```

### axum::middleware (module) › `tower::Service` and custom futures

If you're comfortable implementing your own futures (or want to learn it) and
need as much control as possible then using `tower::Service` without boxed
futures is the way to go.

Use [`tower::Service`] with manual futures to write your middleware when:

- You want your middleware to have the lowest possible overhead.
- Your middleware needs to be configurable for example via builder methods on
  your [`tower::Layer`] such as [`tower_http::trace::TraceLayer`].
- You do intend to publish your middleware as a crate for others to use, perhaps
  as part of tower-http.
- You're comfortable with implementing your own futures, or want to learn how
  the lower levels of async Rust works.

tower's ["Building a middleware from scratch"][tower-from-scratch-guide]
guide is a good place to learn how to do this.

### axum::middleware (module) › Error handling for middleware

axum's error handling model requires handlers to always return a response.
However middleware is one possible way to introduce errors into an application.
If hyper receives an error the connection will be closed without sending a
response. Thus axum requires those errors to be handled gracefully:

```rust
use axum::{
    routing::get,
    error_handling::HandleErrorLayer,
    http::StatusCode,
    BoxError,
    Router,
};
use tower::{ServiceBuilder, timeout::TimeoutLayer};
use std::time::Duration;

async fn handler() {}

let app = Router::new()
    .route("/", get(handler))
    .layer(
        ServiceBuilder::new()
            // this middleware goes above `TimeoutLayer` because it will receive
            // errors returned by `TimeoutLayer`
            .layer(HandleErrorLayer::new(|_: BoxError| async {
                StatusCode::REQUEST_TIMEOUT
            }))
            .layer(TimeoutLayer::new(Duration::from_secs(10)))
    );
# let _: Router = app;
```

See [`error_handling`](crate::error_handling) for more details on axum's error
handling model.

### axum::middleware (module) › Routing to services/middleware and backpressure

Generally routing to one of multiple services and backpressure doesn't mix
well. Ideally you would want ensure a service is ready to receive a request
before calling it. However, in order to know which service to call, you need
the request...

One approach is to not consider the router service itself ready until all
destination services are ready. That is the approach used by
[`tower::steer::Steer`].

Another approach is to always consider all services ready (always return
`Poll::Ready(Ok(()))`) from `Service::poll_ready` and then actually drive
readiness inside the response future returned by `Service::call`. This works
well when your services don't care about backpressure and are always ready
anyway.

axum expects that all services used in your app won't care about
backpressure and so it uses the latter strategy. However that means you
should avoid routing to a service (or using a middleware) that _does_ care
about backpressure. At the very least you should [load shed][tower::load_shed]
so requests are dropped quickly and don't keep piling up.

It also means that if `poll_ready` returns an error then that error will be
returned in the response future from `call` and _not_ from `poll_ready`. In
that case, the underlying service will _not_ be discarded and will continue
to be used for future requests. Services that expect to be discarded if
`poll_ready` fails should _not_ be used with axum.

One possible approach is to only apply backpressure sensitive middleware
around your entire app. This is possible because axum applications are
themselves services:

```rust
use axum::{
    routing::get,
    Router,
};
use tower::ServiceBuilder;
# let some_backpressure_sensitive_middleware =
#     tower::layer::util::Identity::new();

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

let app = Router::new().route("/", get(handler));

let app = ServiceBuilder::new()
    .layer(some_backpressure_sensitive_middleware)
    .service(app);
# let _: Router = app;
```

However when applying middleware around your whole application in this way
you have to take care that errors are still being handled appropriately.

Also note that handlers created from async functions don't care about
backpressure and are always ready. So if you're not using any Tower
middleware you don't have to worry about any of this.

### axum::middleware (module) › Accessing state in middleware

How to make state available to middleware depends on how the middleware is
written.

### axum::middleware (module) › Accessing state in `axum::middleware::from_fn`

Use [`axum::middleware::from_fn_with_state`](crate::middleware::from_fn_with_state).

### axum::middleware (module) › Accessing state in custom `tower::Layer`s

```rust
use axum::{
    Router,
    routing::get,
    middleware::{self, Next},
    response::Response,
    extract::{State, Request},
};
use tower::{Layer, Service};
use std::task::{Context, Poll};

#[derive(Clone)]
struct AppState {}

#[derive(Clone)]
struct MyLayer {
    state: AppState,
}

impl<S> Layer<S> for MyLayer {
    type Service = MyService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        MyService {
            inner,
            state: self.state.clone(),
        }
    }
}

#[derive(Clone)]
struct MyService<S> {
    inner: S,
    state: AppState,
}

impl<S, B> Service<Request<B>> for MyService<S>
where
    S: Service<Request<B>>,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = S::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<B>) -> Self::Future {
        // Do something with `self.state`.
        //
        // See `axum::RequestExt` for how to run extractors directly from
        // a `Request`.

        self.inner.call(req)
    }
}

async fn handler(_: State<AppState>) {}

let state = AppState {};

let app = Router::new()
    .route("/", get(handler))
    .layer(MyLayer { state: state.clone() })
    .with_state(state);
# let _: axum::Router = app;
```

### axum::middleware (module) › Passing state from middleware to handlers

State can be passed from middleware to handlers using [request extensions]:

```rust
use axum::{
    Router,
    http::StatusCode,
    routing::get,
    response::{IntoResponse, Response},
    middleware::{self, Next},
    extract::{Request, Extension},
};

#[derive(Clone)]
struct CurrentUser { /* ... */ }

async fn auth(mut req: Request, next: Next) -> Result<Response, StatusCode> {
    let auth_header = req.headers()
        .get(http::header::AUTHORIZATION)
        .and_then(|header| header.to_str().ok());

    let auth_header = if let Some(auth_header) = auth_header {
        auth_header
    } else {
        return Err(StatusCode::UNAUTHORIZED);
    };

    if let Some(current_user) = authorize_current_user(auth_header).await {
        // insert the current user into a request extension so the handler can
        // extract it
        req.extensions_mut().insert(current_user);
        Ok(next.run(req).await)
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}

async fn authorize_current_user(auth_token: &str) -> Option<CurrentUser> {
    // ...
    # unimplemented!()
}

async fn handler(
    // extract the current user, set by the middleware
    Extension(current_user): Extension<CurrentUser>,
) {
    // ...
}

let app = Router::new()
    .route("/", get(handler))
    .route_layer(middleware::from_fn(auth));
# let _: Router = app;
```

[Response extensions] can also be used but note that request extensions are not
automatically moved to response extensions. You need to manually do that for the
extensions you need.

### axum::middleware (module) › Rewriting request URI in middleware

Middleware added with [`Router::layer`] will run after routing. That means it
cannot be used to run middleware that rewrites the request URI. By the time the
middleware runs the routing is already done.

The workaround is to wrap the middleware around the entire `Router` (this works
because `Router` implements [`Service`]):

```rust
use tower::Layer;
use axum::{
    Router,
    ServiceExt, // for `into_make_service`
    response::Response,
    middleware::Next,
    extract::Request,
};

fn rewrite_request_uri<B>(req: Request<B>) -> Request<B> {
    // ...
    # req
}

// this can be any `tower::Layer`
let middleware = tower::util::MapRequestLayer::new(rewrite_request_uri);

let app = Router::new();

// apply the layer around the whole `Router`
// this way the middleware will run before `Router` receives the request
let app_with_middleware = middleware.layer(app);

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app_with_middleware.into_make_service()).await.unwrap();
# };
```

[`tower`]: https://crates.io/crates/tower
[`tower-http`]: https://crates.io/crates/tower-http
[tower-guides]: https://github.com/tower-rs/tower/tree/master/guides
[`axum::middleware::from_fn`]: fn@crate::middleware::from_fn
[`middleware::from_fn`]: fn@crate::middleware::from_fn
[tower-from-scratch-guide]: https://github.com/tower-rs/tower/blob/master/guides/building-a-middleware-from-scratch.md
[`ServiceBuilder::map_request`]: tower::ServiceBuilder::map_request
[`ServiceBuilder::map_response`]: tower::ServiceBuilder::map_response
[`ServiceBuilder::then`]: tower::ServiceBuilder::then
[`ServiceBuilder::and_then`]: tower::ServiceBuilder::and_then
[`axum::middleware::from_extractor`]: fn@crate::middleware::from_extractor
[`Handler::layer`]: crate::handler::Handler::layer
[`Router::layer`]: crate::routing::Router::layer
[`MethodRouter::layer`]: crate::routing::MethodRouter::layer
[`Router::route_layer`]: crate::routing::Router::route_layer
[`MethodRouter::route_layer`]: crate::routing::MethodRouter::route_layer
[request extensions]: https://docs.rs/http/latest/http/request/struct.Request.html#method.extensions
[Response extensions]: https://docs.rs/http/latest/http/response/struct.Response.html#method.extensions
[`State`]: crate::extract::State
[`Service`]: tower::Service

## axum::middleware::future (module)

Future types.

## axum::response (module)

Types and traits for generating responses.

### axum::response (module) › Building responses

Anything that implements [`IntoResponse`] can be returned from a handler. axum
provides implementations for common types:

```rust,no_run
use axum::{
    Json,
    response::{Html, IntoResponse},
    http::{StatusCode, Uri, header::{self, HeaderMap, HeaderName}},
};

// `()` gives an empty response
async fn empty() {}

// String will get a `text/plain; charset=utf-8` content-type
async fn plain_text(uri: Uri) -> String {
    format!("Hi from {}", uri.path())
}

// Bytes will get a `application/octet-stream` content-type
async fn bytes() -> Vec<u8> {
    vec![1, 2, 3, 4]
}

// `Json` will get a `application/json` content-type and work with anything that
// implements `serde::Serialize`
async fn json() -> Json<Vec<String>> {
    Json(vec!["foo".to_owned(), "bar".to_owned()])
}

// `Html` will get a `text/html` content-type
async fn html() -> Html<&'static str> {
    Html("<p>Hello, World!</p>")
}

// `StatusCode` gives an empty response with that status code
async fn status() -> StatusCode {
    StatusCode::NOT_FOUND
}

// `HeaderMap` gives an empty response with some headers
async fn headers() -> HeaderMap {
    let mut headers = HeaderMap::new();
    headers.insert(header::SERVER, "axum".parse().unwrap());
    headers
}

// An array of tuples also gives headers
async fn array_headers() -> [(HeaderName, &'static str); 2] {
    [
        (header::SERVER, "axum"),
        (header::CONTENT_TYPE, "text/plain")
    ]
}

// Use `impl IntoResponse` to avoid writing the whole type
async fn impl_trait() -> impl IntoResponse {
    [
        (header::SERVER, "axum"),
        (header::CONTENT_TYPE, "text/plain")
    ]
}
```

Additionally you can return tuples to build more complex responses from
individual parts.

```rust,no_run
use axum::{
    Json,
    response::IntoResponse,
    http::{StatusCode, HeaderMap, Uri, header},
    extract::Extension,
};

// `(StatusCode, impl IntoResponse)` will override the status code of the response
async fn with_status(uri: Uri) -> (StatusCode, String) {
    (StatusCode::NOT_FOUND, format!("Not Found: {}", uri.path()))
}

// Use `impl IntoResponse` to avoid having to type the whole type
async fn impl_trait(uri: Uri) -> impl IntoResponse {
    (StatusCode::NOT_FOUND, format!("Not Found: {}", uri.path()))
}

// `(HeaderMap, impl IntoResponse)` to add additional headers
async fn with_headers() -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
    (headers, "foo")
}

// Or an array of tuples to more easily build the headers
async fn with_array_headers() -> impl IntoResponse {
    ([(header::CONTENT_TYPE, "text/plain")], "foo")
}

// Use string keys for custom headers
async fn with_array_headers_custom() -> impl IntoResponse {
    ([("x-custom", "custom")], "foo")
}

// `(StatusCode, headers, impl IntoResponse)` to set status and add headers
// `headers` can be either a `HeaderMap` or an array of tuples
async fn with_status_and_array_headers() -> impl IntoResponse {
    (
        StatusCode::NOT_FOUND,
        [(header::CONTENT_TYPE, "text/plain")],
        "foo",
    )
}

// `(Extension<_>, impl IntoResponse)` to set response extensions
async fn with_status_extensions() -> impl IntoResponse {
    (
        Extension(Foo("foo")),
        "foo",
    )
}

#[derive(Clone)]
struct Foo(&'static str);

// Or mix and match all the things
async fn all_the_things(uri: Uri) -> impl IntoResponse {
    let mut header_map = HeaderMap::new();
    if uri.path() == "/" {
        header_map.insert(header::SERVER, "axum".parse().unwrap());
    }

    (
        // set status code
        StatusCode::NOT_FOUND,
        // headers with an array
        [("x-custom", "custom")],
        // some extensions
        Extension(Foo("foo")),
        Extension(Foo("bar")),
        // more headers, built dynamically
        header_map,
        // and finally the body
        "foo",
    )
}
```

In general you can return tuples like:

- `(StatusCode, impl IntoResponse)`
- `(Parts, impl IntoResponse)`
- `(Response<()>, impl IntoResponse)`
- `(T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`].
- `(StatusCode, T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`].
- `(Parts, T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`].
- `(Response<()>, T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`].

This means you cannot accidentally override the status or body as [`IntoResponseParts`] only allows
setting headers and extensions.

Use [`Response`] for more low level control:

```rust,no_run
use axum::{
    Json,
    response::{IntoResponse, Response},
    body::Body,
    http::StatusCode,
};

async fn response() -> Response {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .header("x-foo", "custom header")
        .body(Body::from("not found"))
        .unwrap()
}
```

### axum::response (module) › Returning different response types

If you need to return multiple response types, and `Result<T, E>` isn't appropriate, you can call
`.into_response()` to turn things into `axum::response::Response`:

```rust
use axum::{
    response::{IntoResponse, Redirect, Response},
    http::StatusCode,
};

async fn handle() -> Response {
    if something() {
        "All good!".into_response()
    } else if something_else() {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Something went wrong...",
        ).into_response()
    } else {
        Redirect::to("/").into_response()
    }
}

fn something() -> bool {
    // ...
    # true
}

fn something_else() -> bool {
    // ...
    # true
}
```

### axum::response (module) › Regarding `impl IntoResponse`

You can use `impl IntoResponse` as the return type from handlers to avoid
typing large types. For example

```rust
use axum::http::StatusCode;

async fn handler() -> (StatusCode, [(&'static str, &'static str); 1], &'static str) {
    (StatusCode::OK, [("x-foo", "bar")], "Hello, World!")
}
```

Becomes easier using `impl IntoResponse`:

```rust
use axum::{http::StatusCode, response::IntoResponse};

async fn impl_into_response() -> impl IntoResponse {
    (StatusCode::OK, [("x-foo", "bar")], "Hello, World!")
}
```

However `impl IntoResponse` has a few limitations. Firstly it can only be used
to return a single type:

```rust,compile_fail
use axum::{http::StatusCode, response::IntoResponse};

async fn handler() -> impl IntoResponse {
    if check_something() {
        StatusCode::NOT_FOUND
    } else {
        "Hello, World!"
    }
}

fn check_something() -> bool {
    # false
    // ...
}
```

This function returns either a `StatusCode` or a `&'static str` which `impl
Trait` doesn't allow.

Secondly `impl IntoResponse` can lead to type inference issues when used with
`Result` and `?`:

```rust,compile_fail
use axum::{http::StatusCode, response::IntoResponse};

async fn handler() -> impl IntoResponse {
    create_thing()?;
    Ok(StatusCode::CREATED)
}

fn create_thing() -> Result<(), StatusCode> {
    # Ok(())
    // ...
}
```

This is because `?` supports using the [`From`] trait to convert to a different
error type but it doesn't know which type to convert to, because we only
specified `impl IntoResponse` as the return type.

`Result<impl IntoResponse, impl IntoResponse>` doesn't always work either:

```rust,compile_fail
use axum::{http::StatusCode, response::IntoResponse};

async fn handler() -> Result<impl IntoResponse, impl IntoResponse> {
    create_thing()?;
    Ok(StatusCode::CREATED)
}

fn create_thing() -> Result<(), StatusCode> {
    # Ok(())
    // ...
}
```

The solution is to use a concrete error type, such as `Result<impl IntoResponse, StatusCode>`:

```rust
use axum::{http::StatusCode, response::IntoResponse};

async fn handler() -> Result<impl IntoResponse, StatusCode> {
    create_thing()?;
    Ok(StatusCode::CREATED)
}

fn create_thing() -> Result<(), StatusCode> {
    # Ok(())
    // ...
}
```

Because of this it is generally not recommended to use `impl IntoResponse`
unless you're familiar with the details of how `impl Trait` works.

[`IntoResponse`]: crate::response::IntoResponse
[`IntoResponseParts`]: crate::response::IntoResponseParts
[`StatusCode`]: http::StatusCode

## axum::response::sse (module)

Server-Sent Events (SSE) responses.

### axum::response::sse (module) › Example

```
use axum::{
    Router,
    routing::get,
    response::sse::{Event, KeepAlive, Sse},
};
use std::{time::Duration, convert::Infallible};
use tokio_stream::StreamExt as _ ;
use futures_util::stream::{self, Stream};

let app = Router::new().route("/sse", get(sse_handler));

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    // A `Stream` that repeats an event every second
    let stream = stream::repeat_with(|| Event::default().data("hi!"))
        .map(Ok)
        .throttle(Duration::from_secs(1));

    Sse::new(stream).keep_alive(KeepAlive::default())
}
# let _: Router = app;
```

## axum::routing (module)

Routing between [`Service`]s and handlers.

## axum::routing::future (module)

Future types.

## axum::routing::method_routing (module)

Route to services and handlers based on HTTP methods.

## axum::serve (module)

Serve services.

## axum::Addr (assoc_type)

The listener's address type.

## axum::DEFAULT_KEEP_ALIVE (assoc_const)

Default keep-alive event

## axum::DELETE (assoc_const)

Match `DELETE` requests.

## axum::Future (assoc_type)

The type of future calling this handler returns.

## axum::GET (assoc_const)

Match `GET` requests.

## axum::HEAD (assoc_const)

Match `HEAD` requests.

## axum::Io (assoc_type)

The listener's IO type.

## axum::OPTIONS (assoc_const)

Match `OPTIONS` requests.

## axum::PATCH (assoc_const)

Match `PATCH` requests.

## axum::POST (assoc_const)

Match `POST` requests.

## axum::PUT (assoc_const)

Match `PUT` requests.

## axum::TRACE (assoc_const)

Match `TRACE` requests.

## axum::accept (function)

Accept a new incoming connection to this listener.

If the underlying accept call can return an error, this function must
take care of logging and retrying.

## axum::accept_unmasked_frames (function)

Allow server to accept unmasked frames (defaults to false)

## axum::as_str (function)

Returns a `str` representation of the path.

## axum::as_str (function)

Returns a `str` representation of the path.

## axum::as_str (function)

Returns as a string slice.

## axum::binary (function)

Create a new binary WebSocket message by converting to `Bytes`.

## axum::body::to_bytes (function)

Converts [`Body`] into [`Bytes`] and limits the maximum size of the body.

### axum::body::to_bytes (function) › Example

```rust
use axum::body::{to_bytes, Body};

# async fn foo() -> Result<(), axum_core::Error> {
let body = Body::from(vec![1, 2, 3]);
// Use `usize::MAX` if you don't care about the maximum size.
let bytes = to_bytes(body, usize::MAX).await?;
assert_eq!(&bytes[..], &[1, 2, 3]);
# Ok(())
# }
```

You can detect if the limit was hit by checking the source of the error:

```rust
use axum::body::{to_bytes, Body};
use http_body_util::LengthLimitError;

# #[tokio::main]
# async fn main() {
let body = Body::from(vec![1, 2, 3]);
match to_bytes(body, 1).await {
    Ok(_bytes) => panic!("should have hit the limit"),
    Err(err) => {
        let source = std::error::Error::source(&err).unwrap();
        assert!(source.is::<LengthLimitError>());
    }
}
# }
```

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::body_text (function)

Get the response body text used for this rejection.

## axum::bytes (function)

Get the full data of the field as [`Bytes`].

## axum::call (function)

Call the callback.

## axum::call (function)

Call the handler with the given request.

## axum::chunk (function)

Stream a chunk of the field data.

When the field data has been exhausted, this will return [`None`].

Note this does the same thing as `Field`'s [`Stream`] implementation.

### axum::chunk (function) › Example

```
use axum::{
   extract::Multipart,
   routing::post,
   response::IntoResponse,
   http::StatusCode,
   Router,
};

async fn upload(mut multipart: Multipart) -> Result<(), (StatusCode, String)> {
    while let Some(mut field) = multipart
        .next_field()
        .await
        .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?
    {
        while let Some(chunk) = field
            .chunk()
            .await
            .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?
        {
            println!("received {} bytes", chunk.len());
        }
    }

    Ok(())
}

let app = Router::new().route("/upload", post(upload));
# let _: Router = app;
```

## axum::code (struct_field)

The reason as a code.

## axum::comment (function)

Set the event's comment field (`:<comment-text>`).

This field will be ignored by most SSE clients.

Unlike other functions, this function can be called multiple times to add many comments.

### axum::comment (function) › Panics

Panics if `comment` contains any newlines or carriage returns, as they are not allowed in
comments.

## axum::connect (function)

Chain an additional handler that will only accept `CONNECT` requests.

See [`MethodFilter::CONNECT`] for when you'd want to use this,
and [`MethodRouter::get`] for an example.

## axum::connect_info (function)

Create type holding information about the connection.

## axum::connect_service (function)

Chain an additional service that will only accept `CONNECT` requests.

See [`MethodFilter::CONNECT`] for when you'd want to use this,
and [`MethodRouter::get_service`] for an example.

## axum::content_type (function)

Get the [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of the field.

## axum::delete (function)

Chain an additional handler that will only accept `DELETE` requests.

 See [`MethodRouter::get`] for an example.

## axum::delete_service (function)

Chain an additional service that will only accept `DELETE` requests.

 See [`MethodRouter::get_service`] for an example.

## axum::deref (function)

```
/// Example fn that takes a str slice
fn a(s: &str) {}

let data = axum::extract::ws::Utf8Bytes::from_static("foo123");

// auto-deref as arg
a(&data);

// deref to str methods
assert_eq!(data.len(), 6);
```

## axum::eq (function)

```
let payload = axum::extract::ws::Utf8Bytes::from_static("foo123");
assert_eq!(payload, "foo123");
assert_eq!(payload, "foo123".to_string());
assert_eq!(payload, &"foo123".to_string());
assert_eq!(payload, std::borrow::Cow::from("foo123"));
```

## axum::error_handling::HandleError (struct)

A [`Service`] adapter that handles errors by converting them into responses.

See [module docs](self) for more details on axum's error handling model.

## axum::error_handling::HandleErrorLayer (struct)

[`Layer`] that applies [`HandleError`] which is a [`Service`] adapter
that handles errors by converting them into responses.

See [module docs](self) for more details on axum's error handling model.

## axum::error_handling::future::HandleErrorFuture (struct)

Response future for [`HandleError`].

## axum::event (function)

Customize the event of the keep-alive message.

Default is an empty comment.

### axum::event (function) › Panics

Panics if `event` contains any newline or carriage returns, as they are not allowed in SSE
comments.

## axum::event (function)

Set the event's name field (`event:<event-name>`).

This corresponds to the `type` parameter given when calling `addEventListener` on an
[`EventSource`]. For example, `.event("update")` should correspond to
`.addEventListener("update", ...)`. If no event type is given, browsers will fire a
[`message` event] instead.

[`EventSource`]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource
[`message` event]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource/message_event

### axum::event (function) › Panics

- Panics if `event` contains any newlines or carriage returns.
- Panics if this function has already been called on this event.

## axum::expected (struct_field)

The number of expected parameters.

## axum::expected_type (struct_field)

The expected type of the value.

## axum::expected_type (struct_field)

The expected type of the value.

## axum::expected_type (struct_field)

The expected type of the value.

## axum::extension::AddExtension (struct)

Middleware for adding some shareable value to [request extensions].

See [Passing state from middleware to handlers](index.html#passing-state-from-middleware-to-handlers)
for more details.

[request extensions]: https://docs.rs/http/latest/http/struct.Extensions.html

If you need a layer to add an extension to every request,
use the [Layer](tower::Layer) implementation of [Extension].

## axum::extension::Extension (struct)

Extractor and response for extensions.

### axum::extension::Extension (struct) › As extractor

This is commonly used to share state across handlers.

```rust,no_run
use axum::{
    Router,
    Extension,
    routing::get,
};
use std::sync::Arc;

// Some shared state used throughout our application
struct State {
    // ...
}

async fn handler(state: Extension<Arc<State>>) {
    // ...
}

let state = Arc::new(State { /* ... */ });

let app = Router::new().route("/", get(handler))
    // Add middleware that inserts the state into all incoming request's
    // extensions.
    .layer(Extension(state));
# let _: Router = app;
```

If the extension is missing it will reject the request with a `500 Internal
Server Error` response. Alternatively, you can use `Option<Extension<T>>` to
make the extension extractor optional.

### axum::extension::Extension (struct) › As response

Response extensions can be used to share state with middleware.

```rust
use axum::{
    Extension,
    response::IntoResponse,
};

async fn handler() -> (Extension<Foo>, &'static str) {
    (
        Extension(Foo("foo")),
        "Hello, World!"
    )
}

#[derive(Clone)]
struct Foo(&'static str);
```

## axum::extract::connect_info::ConnectInfo (struct)

Extractor for getting connection information produced by a [`Connected`].

Note this extractor requires you to use
[`Router::into_make_service_with_connect_info`] to run your app
otherwise it will fail at runtime.

See [`Router::into_make_service_with_connect_info`] for more details.

[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info

## axum::extract::connect_info::Connected (trait)

Trait that connected IO resources implement and use to produce information
about the connection.

The goal for this trait is to allow users to implement custom IO types that
can still provide the same connection metadata.

See [`Router::into_make_service_with_connect_info`] for more details.

[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info

## axum::extract::connect_info::IntoMakeServiceWithConnectInfo (struct)

A [`MakeService`] created from a router.

See [`Router::into_make_service_with_connect_info`] for more details.

[`MakeService`]: tower::make::MakeService
[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info

## axum::extract::connect_info::MockConnectInfo (struct)

Middleware used to mock [`ConnectInfo`] during tests.

If you're accidentally using [`MockConnectInfo`] and
[`Router::into_make_service_with_connect_info`] at the same time then
[`Router::into_make_service_with_connect_info`] takes precedence.

### axum::extract::connect_info::MockConnectInfo (struct) › Example

```
use axum::{
    Router,
    extract::connect_info::{MockConnectInfo, ConnectInfo},
    body::Body,
    routing::get,
    http::{Request, StatusCode},
};
use std::net::SocketAddr;
use tower::ServiceExt;

async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) {}

// this router you can run with `app.into_make_service_with_connect_info::<SocketAddr>()`
fn app() -> Router {
    Router::new().route("/", get(handler))
}

// use this router for tests
fn test_app() -> Router {
    app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337))))
}

// #[tokio::test]
async fn some_test() {
    let app = test_app();

    let request = Request::new(Body::empty());
    let response = app.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}
#
# #[tokio::main]
# async fn main() {
#     some_test().await;
# }
```

[`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info

## axum::extract::connect_info::ResponseFuture (struct)

Response future for [`IntoMakeServiceWithConnectInfo`].

## axum::extract::matched_path::MatchedPath (struct)

Access the path in the router that matches the request.

```
use axum::{
    Router,
    extract::MatchedPath,
    routing::get,
};

let app = Router::new().route(
    "/users/{id}",
    get(|path: MatchedPath| async move {
        let path = path.as_str();
        // `path` will be "/users/{id}"
    })
);
# let _: Router = app;
```

### axum::extract::matched_path::MatchedPath (struct) › Accessing `MatchedPath` via extensions

`MatchedPath` can also be accessed from middleware via request extensions.

This is useful for example with [`Trace`](tower_http::trace::Trace) to
create a span that contains the matched path:

```
use axum::{
    Router,
    extract::{Request, MatchedPath},
    routing::get,
};
use tower_http::trace::TraceLayer;

let app = Router::new()
    .route("/users/{id}", get(|| async { /* ... */ }))
    .layer(
        TraceLayer::new_for_http().make_span_with(|req: &Request<_>| {
            let path = if let Some(path) = req.extensions().get::<MatchedPath>() {
                path.as_str()
            } else {
                req.uri().path()
            };
            tracing::info_span!("http-request", %path)
        }),
    );
# let _: Router = app;
```

## axum::extract::multipart::Field (struct)

A single field in a multipart stream.

## axum::extract::multipart::InvalidBoundary (struct)

Rejection type used if the `boundary` in a `multipart/form-data` is
missing or invalid.

## axum::extract::multipart::Multipart (struct)

Extractor that parses `multipart/form-data` requests (commonly used with file uploads).

⚠️ Since extracting multipart form data from the request requires consuming the body, the
`Multipart` extractor must be *last* if there are multiple extractors in a handler.
See ["the order of extractors"][order-of-extractors]

[order-of-extractors]: crate::extract#the-order-of-extractors

### axum::extract::multipart::Multipart (struct) › Example

```rust,no_run
use axum::{
    extract::Multipart,
    routing::post,
    Router,
};
use futures_util::stream::StreamExt;

async fn upload(mut multipart: Multipart) {
    while let Some(mut field) = multipart.next_field().await.unwrap() {
        let name = field.name().unwrap().to_string();
        let data = field.bytes().await.unwrap();

        println!("Length of `{}` is {} bytes", name, data.len());
    }
}

let app = Router::new().route("/upload", post(upload));
# let _: Router = app;
```

### axum::extract::multipart::Multipart (struct) › Large Files

For security reasons, by default, `Multipart` limits the request body size to 2MB.
See [`DefaultBodyLimit`][default-body-limit] for how to configure this limit.

[default-body-limit]: crate::extract::DefaultBodyLimit

## axum::extract::multipart::MultipartError (struct)

Errors associated with parsing `multipart/form-data` requests.

## axum::extract::multipart::MultipartRejection (enum)

Rejection used for [`Multipart`].

Contains one variant for each way the [`Multipart`] extractor can fail.

## axum::extract::nested_path::NestedPath (struct)

Access the path the matched the route is nested at.

This can for example be used when doing redirects.

### axum::extract::nested_path::NestedPath (struct) › Example

```
use axum::{
    Router,
    extract::NestedPath,
    routing::get,
};

let api = Router::new().route(
    "/users",
    get(|path: NestedPath| async move {
        // `path` will be "/api" because that's what this
        // router is nested at when we build `app`
        let path = path.as_str();
    })
);

let app = Router::new().nest("/api", api);
# let _: Router = app;
```

## axum::extract::original_uri::OriginalUri (struct)

Extractor that gets the original request URI regardless of nesting.

This is necessary since [`Uri`](http::Uri), when used as an extractor, will
have the prefix stripped if used in a nested service.

### axum::extract::original_uri::OriginalUri (struct) › Example

```
use axum::{
    routing::get,
    Router,
    extract::OriginalUri,
    http::Uri
};

let api_routes = Router::new()
    .route(
        "/users",
        get(|uri: Uri, OriginalUri(original_uri): OriginalUri| async {
            // `uri` is `/users`
            // `original_uri` is `/api/users`
        }),
    );

let app = Router::new().nest("/api", api_routes);
# let _: Router = app;
```

### axum::extract::original_uri::OriginalUri (struct) › Extracting via request extensions

`OriginalUri` can also be accessed from middleware via request extensions.
This is useful for example with [`Trace`](tower_http::trace::Trace) to
create a span that contains the full path, if your service might be nested:

```
use axum::{
    Router,
    extract::OriginalUri,
    http::Request,
    routing::get,
};
use tower_http::trace::TraceLayer;

let api_routes = Router::new()
    .route("/users/{id}", get(|| async { /* ... */ }))
    .layer(
        TraceLayer::new_for_http().make_span_with(|req: &Request<_>| {
            let path = if let Some(path) = req.extensions().get::<OriginalUri>() {
                // This will include `/api`
                path.0.path().to_owned()
            } else {
                // The `OriginalUri` extension will always be present if using
                // `Router` unless another extractor or middleware has removed it
                req.uri().path().to_owned()
            };
            tracing::info_span!("http-request", %path)
        }),
    );

let app = Router::new().nest("/api", api_routes);
# let _: Router = app;
```

## axum::extract::path::ErrorKind (enum)

The kinds of errors that can happen we deserializing into a [`Path`].

This type is obtained through [`FailedToDeserializePathParams::kind`] or
[`FailedToDeserializePathParams::into_kind`] and is useful for building
more precise error messages.

## axum::extract::path::ErrorKind::DeserializeError (variant)

Failed to deserialize the value with a custom deserialization error.

## axum::extract::path::ErrorKind::InvalidUtf8InPathParam (variant)

A parameter contained text that, once percent decoded, wasn't valid UTF-8.

## axum::extract::path::ErrorKind::Message (variant)

Catch-all variant for errors that don't fit any other variant.

## axum::extract::path::ErrorKind::ParseError (variant)

Failed to parse a value into the expected type.

This variant is used when deserializing into a primitive type (such as `String` and `u32`).

## axum::extract::path::ErrorKind::ParseErrorAtIndex (variant)

Failed to parse the value at a specific index into the expected type.

This variant is used when deserializing into sequence types, such as tuples.

## axum::extract::path::ErrorKind::ParseErrorAtKey (variant)

Failed to parse the value at a specific key into the expected type.

This variant is used when deserializing into types that have named fields, such as structs.

## axum::extract::path::ErrorKind::UnsupportedType (variant)

Tried to serialize into an unsupported type such as nested maps.

This error kind is caused by programmer errors and thus gets converted into a `500 Internal
Server Error` response.

## axum::extract::path::ErrorKind::WrongNumberOfParameters (variant)

The URI contained the wrong number of parameters.

## axum::extract::path::FailedToDeserializePathParams (struct)

Rejection type for [`Path`] if the captured routes params couldn't be deserialized
into the expected type.

## axum::extract::path::FailedToDeserializePathParams::into_kind (function)

Convert this error into the underlying error kind.

## axum::extract::path::FailedToDeserializePathParams::kind (function)

Get a reference to the underlying error kind.

## axum::extract::path::InvalidUtf8InPathParam (struct)

Rejection used by [`RawPathParams`] if a parameter contained text that, once percent decoded,
wasn't valid UTF-8.

## axum::extract::path::Path (struct)

Extractor that will get captures from the URL and parse them using
[`serde`].

Any percent encoded parameters will be automatically decoded. The decoded
parameters must be valid UTF-8, otherwise `Path` will fail and return a `400
Bad Request` response.

### axum::extract::path::Path (struct) › `Option<Path<T>>` behavior

You can use `Option<Path<T>>` as an extractor to allow the same handler to
be used in a route with parameters that deserialize to `T`, and another
route with no parameters at all.

### axum::extract::path::Path (struct) › Example

These examples assume the `serde` feature of the [`uuid`] crate is enabled.

One `Path` can extract multiple captures. It is not necessary (and does
not work) to give a handler more than one `Path` argument.

[`uuid`]: https://crates.io/crates/uuid

```rust,no_run
use axum::{
    extract::Path,
    routing::get,
    Router,
};
use uuid::Uuid;

async fn users_teams_show(
    Path((user_id, team_id)): Path<(Uuid, Uuid)>,
) {
    // ...
}

let app = Router::new().route("/users/{user_id}/team/{team_id}", get(users_teams_show));
# let _: Router = app;
```

If the path contains only one parameter, then you can omit the tuple.

```rust,no_run
use axum::{
    extract::Path,
    routing::get,
    Router,
};
use uuid::Uuid;

async fn user_info(Path(user_id): Path<Uuid>) {
    // ...
}

let app = Router::new().route("/users/{user_id}", get(user_info));
# let _: Router = app;
```

Path segments also can be deserialized into any type that implements
[`serde::Deserialize`]. This includes tuples and structs:

```rust,no_run
use axum::{
    extract::Path,
    routing::get,
    Router,
};
use serde::Deserialize;
use uuid::Uuid;

// Path segment labels will be matched with struct field names
#[derive(Deserialize)]
struct Params {
    user_id: Uuid,
    team_id: Uuid,
}

async fn users_teams_show(
    Path(Params { user_id, team_id }): Path<Params>,
) {
    // ...
}

// When using tuples the path segments will be matched by their position in the route
async fn users_teams_create(
    Path((user_id, team_id)): Path<(String, String)>,
) {
    // ...
}

let app = Router::new().route(
    "/users/{user_id}/team/{team_id}",
    get(users_teams_show).post(users_teams_create),
);
# let _: Router = app;
```

If you wish to capture all path parameters you can use `HashMap` or `Vec`:

```rust,no_run
use axum::{
    extract::Path,
    routing::get,
    Router,
};
use std::collections::HashMap;

async fn params_map(
    Path(params): Path<HashMap<String, String>>,
) {
    // ...
}

async fn params_vec(
    Path(params): Path<Vec<(String, String)>>,
) {
    // ...
}

let app = Router::new()
    .route("/users/{user_id}/team/{team_id}", get(params_map).post(params_vec));
# let _: Router = app;
```

### axum::extract::path::Path (struct) › Providing detailed rejection output

If the URI cannot be deserialized into the target type the request will be rejected and an
error response will be returned. See [`customize-path-rejection`] for an example of how to customize that error.

[`serde`]: https://crates.io/crates/serde
[`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html
[`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs

## axum::extract::path::RawPathParams (struct)

Extractor that will get captures from the URL without deserializing them.

In general you should prefer to use [`Path`] as it is higher level, however `RawPathParams` is
suitable if just want the raw params without deserializing them and thus saving some
allocations.

Any percent encoded parameters will be automatically decoded. The decoded parameters must be
valid UTF-8, otherwise `RawPathParams` will fail and return a `400 Bad Request` response.

### axum::extract::path::RawPathParams (struct) › Example

```rust,no_run
use axum::{
    extract::RawPathParams,
    routing::get,
    Router,
};

async fn users_teams_show(params: RawPathParams) {
    for (key, value) in &params {
        println!("{key:?} = {value:?}");
    }
}

let app = Router::new().route("/users/{user_id}/team/{team_id}", get(users_teams_show));
# let _: Router = app;
```

## axum::extract::path::RawPathParams::iter (function)

Get an iterator over the path parameters.

## axum::extract::path::RawPathParamsIter (struct)

An iterator over raw path parameters.

Created with [`RawPathParams::iter`].

## axum::extract::query::Query (struct)

Extractor that deserializes query strings into some type.

`T` is expected to implement [`serde::Deserialize`].

### axum::extract::query::Query (struct) › Examples

```rust,no_run
use axum::{
    extract::Query,
    routing::get,
    Router,
};
use serde::Deserialize;

#[derive(Deserialize)]
struct Pagination {
    page: usize,
    per_page: usize,
}

// This will parse query strings like `?page=2&per_page=30` into `Pagination`
// structs.
async fn list_things(pagination: Query<Pagination>) {
    let pagination: Pagination = pagination.0;

    // ...
}

let app = Router::new().route("/list_things", get(list_things));
# let _: Router = app;
```

If the query string cannot be parsed it will reject the request with a `400
Bad Request` response.

For handling values being empty vs missing see the [query-params-with-empty-strings][example]
example.

[example]: https://github.com/tokio-rs/axum/blob/v0.8.x/examples/query-params-with-empty-strings/src/main.rs

For handling multiple values for the same query parameter, in a `?foo=1&foo=2&foo=3`
fashion, use [`axum_extra::extract::Query`] instead.

[`axum_extra::extract::Query`]: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.Query.html

## axum::extract::raw_form::RawForm (struct)

Extractor that extracts raw form requests.

For `GET` requests it will extract the raw query. For other methods it extracts the raw
`application/x-www-form-urlencoded` encoded request body.

### axum::extract::raw_form::RawForm (struct) › Example

```rust,no_run
use axum::{
    extract::RawForm,
    routing::get,
    Router
};

async fn handler(RawForm(form): RawForm) {}

let app = Router::new().route("/", get(handler));
# let _: Router = app;
```

## axum::extract::raw_query::RawQuery (struct)

Extractor that extracts the raw query string, without parsing it.

### axum::extract::raw_query::RawQuery (struct) › Example

```rust,no_run
use axum::{
    extract::RawQuery,
    routing::get,
    Router,
};
use futures_util::StreamExt;

async fn handler(RawQuery(query): RawQuery) {
    // ...
}

let app = Router::new().route("/users", get(handler));
# let _: Router = app;
```

## axum::extract::rejection::ExtensionRejection (enum)

Rejection used for [`Extension`](super::Extension).

Contains one variant for each way the [`Extension`](super::Extension) extractor
can fail.

## axum::extract::rejection::FailedToDeserializeForm (struct)

Rejection type used if the [`Form`](super::Form) extractor is unable to
deserialize the form into the target type.

## axum::extract::rejection::FailedToDeserializeFormBody (struct)

Rejection type used if the [`Form`](super::Form) extractor is unable to
deserialize the form body into the target type.

## axum::extract::rejection::FailedToDeserializeQueryString (struct)

Rejection type used if the [`Query`](super::Query) extractor is unable to
deserialize the query string into the target type.

## axum::extract::rejection::FormRejection (enum)

Rejection used for [`Form`](super::Form).

Contains one variant for each way the [`Form`](super::Form) extractor
can fail.

## axum::extract::rejection::InvalidFormContentType (struct)

Rejection type for [`Form`](super::Form) or [`RawForm`](super::RawForm)
used if the `Content-Type` header is missing
or its value is not `application/x-www-form-urlencoded`.

## axum::extract::rejection::JsonDataError (struct)

Rejection type for [`Json`](super::Json).

This rejection is used if the request body is syntactically valid JSON but couldn't be
deserialized into the target type.

## axum::extract::rejection::JsonRejection (enum)

Rejection used for [`Json`](super::Json).

Contains one variant for each way the [`Json`](super::Json) extractor
can fail.

## axum::extract::rejection::JsonSyntaxError (struct)

Rejection type for [`Json`](super::Json).

This rejection is used if the request body didn't contain syntactically valid JSON.

## axum::extract::rejection::MatchedPathMissing (struct)

Rejection if no matched path could be found.

See [`MatchedPath`](super::MatchedPath) for more details.

## axum::extract::rejection::MatchedPathRejection (enum)

Rejection used for [`MatchedPath`](super::MatchedPath).

## axum::extract::rejection::MissingExtension (struct)

Rejection type for [`Extension`](super::Extension) if an expected
request extension was not found.

## axum::extract::rejection::MissingJsonContentType (struct)

Rejection type for [`Json`](super::Json) used if the `Content-Type`
header is missing.

## axum::extract::rejection::MissingPathParams (struct)

Rejection type used if axum's internal representation of path parameters
is missing. This is commonly caused by extracting `Request<_>`. `Path`
must be extracted first.

## axum::extract::rejection::NestedPathRejection (struct)

Rejection type for [`NestedPath`](super::NestedPath).

This rejection is used if the matched route wasn't nested.

## axum::extract::rejection::PathRejection (enum)

Rejection used for [`Path`](super::Path).

Contains one variant for each way the [`Path`](super::Path) extractor
can fail.

## axum::extract::rejection::QueryRejection (enum)

Rejection used for [`Query`](super::Query).

Contains one variant for each way the [`Query`](super::Query) extractor
can fail.

## axum::extract::rejection::RawFormRejection (enum)

Rejection used for [`RawForm`](super::RawForm).

Contains one variant for each way the [`RawForm`](super::RawForm) extractor
can fail.

## axum::extract::rejection::RawPathParamsRejection (enum)

Rejection used for [`RawPathParams`](super::RawPathParams).

Contains one variant for each way the [`RawPathParams`](super::RawPathParams) extractor
can fail.

## axum::extract::state::State (struct)

Extractor for state.

See ["Sharing state with handlers"][sharing-state] for an overview of all approaches to
sharing state, including when to use `Arc`, how `FromRef` substates work, and what the
`Router<S>` type parameter means.

See ["Accessing state in middleware"][state-from-middleware] for how to
access state in middleware.

State is global and used in every request a router with state receives.
For accessing data derived from requests, such as authorization data, see [`Extension`].

[sharing-state]: crate#sharing-state-with-handlers
[state-from-middleware]: crate::middleware#accessing-state-in-middleware
[`Extension`]: crate::Extension

### axum::extract::state::State (struct) › With `Router`

```
use axum::{Router, routing::get, extract::State};

// the application state
//
// here you can put configuration, database connection pools, or whatever
// state you need
#[derive(Clone)]
struct AppState {}

let state = AppState {};

// create a `Router` that holds our state
let app = Router::new()
    .route("/", get(handler))
    // provide the state so the router can access it
    .with_state(state);

async fn handler(
    // access the state via the `State` extractor
    // extracting a state of the wrong type results in a compile error
    State(state): State<AppState>,
) {
    // use `state`...
}
# let _: axum::Router = app;
```

Note that `State` is an extractor, so be sure to put it before any body
extractors, see ["the order of extractors"][order-of-extractors].

[order-of-extractors]: crate::extract#the-order-of-extractors

### axum::extract::state::State (struct) › Combining stateful routers

Multiple [`Router`]s can be combined with [`Router::nest`] or [`Router::merge`]
When combining [`Router`]s with one of these methods, the [`Router`]s must have
the same state type. Generally, this can be inferred automatically:

```
use axum::{Router, routing::get, extract::State};

#[derive(Clone)]
struct AppState {}

let state = AppState {};

// create a `Router` that will be nested within another
let api = Router::new()
    .route("/posts", get(posts_handler));

let app = Router::new()
    .nest("/api", api)
    .with_state(state);

async fn posts_handler(State(state): State<AppState>) {
    // use `state`...
}
# let _: axum::Router = app;
```

However, if you are composing [`Router`]s that are defined in separate scopes,
you may need to annotate the [`State`] type explicitly:

```
use axum::{Router, routing::get, extract::State};

#[derive(Clone)]
struct AppState {}

fn make_app() -> Router {
    let state = AppState {};

    Router::new()
        .nest("/api", make_api())
        .with_state(state) // the outer Router's state is inferred
}

// the inner Router must specify its state type to compose with the
// outer router
fn make_api() -> Router<AppState> {
    Router::new()
        .route("/posts", get(posts_handler))
}

async fn posts_handler(State(state): State<AppState>) {
    // use `state`...
}
# let _: axum::Router = make_app();
```

In short, a [`Router`]'s generic state type defaults to `()`
(no state) unless [`Router::with_state`] is called or the value
of the generic type is given explicitly.

[`Router`]: crate::Router
[`Router::merge`]: crate::Router::merge
[`Router::nest`]: crate::Router::nest
[`Router::with_state`]: crate::Router::with_state

### axum::extract::state::State (struct) › With `MethodRouter`

```
use axum::{routing::get, extract::State};

#[derive(Clone)]
struct AppState {}

let state = AppState {};

let method_router_with_state = get(handler)
    // provide the state so the handler can access it
    .with_state(state);
# let _: axum::routing::MethodRouter = method_router_with_state;

async fn handler(State(state): State<AppState>) {
    // use `state`...
}
```

### axum::extract::state::State (struct) › With `Handler`

```
use axum::{routing::get, handler::Handler, extract::State};

#[derive(Clone)]
struct AppState {}

let state = AppState {};

async fn handler(State(state): State<AppState>) {
    // use `state`...
}

// provide the state so the handler can access it
let handler_with_state = handler.with_state(state);

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, handler_with_state.into_make_service()).await.unwrap();
# };
```

### axum::extract::state::State (struct) › Substates

[`State`] only allows a single state type but you can use [`FromRef`] to extract "substates":

```
use axum::{Router, routing::get, extract::{State, FromRef}};

// the application state
#[derive(Clone)]
struct AppState {
    // that holds some api specific state
    api_state: ApiState,
}

// the api specific state
#[derive(Clone)]
struct ApiState {}

// support converting an `AppState` in an `ApiState`
impl FromRef<AppState> for ApiState {
    fn from_ref(app_state: &AppState) -> ApiState {
        app_state.api_state.clone()
    }
}

let state = AppState {
    api_state: ApiState {},
};

let app = Router::new()
    .route("/", get(handler))
    .route("/api/users", get(api_users))
    .with_state(state);

async fn api_users(
    // access the api specific state
    State(api_state): State<ApiState>,
) {
}

async fn handler(
    // we can still access to top level state
    State(state): State<AppState>,
) {
}
# let _: axum::Router = app;
```

For convenience `FromRef` can also be derived using `#[derive(FromRef)]`.

### axum::extract::state::State (struct) › For library authors

If you're writing a library that has an extractor that needs state, this is the recommended way
to do it:

```rust
use axum_core::extract::{FromRequestParts, FromRef};
use http::request::Parts;
use std::convert::Infallible;

// the extractor your library provides
struct MyLibraryExtractor;

impl<S> FromRequestParts<S> for MyLibraryExtractor
where
    // keep `S` generic but require that it can produce a `MyLibraryState`
    // this means users will have to implement `FromRef<UserState> for MyLibraryState`
    MyLibraryState: FromRef<S>,
    S: Send + Sync,
{
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        // get a `MyLibraryState` from a reference to the state
        let state = MyLibraryState::from_ref(state);

        // ...
        # todo!()
    }
}

// the state your library needs
struct MyLibraryState {
    // ...
}
```

### axum::extract::state::State (struct) › Shared mutable state

[As state is global within a `Router`][global] you can't directly get a mutable reference to
the state.

The most basic solution is to use an `Arc<Mutex<_>>`. Which kind of mutex you need depends on
your use case. See [the tokio docs] for more details.

Note that holding a locked `std::sync::Mutex` across `.await` points will result in `!Send`
futures which are incompatible with axum. If you need to hold a mutex across `.await` points,
consider using a `tokio::sync::Mutex` instead.

### axum::extract::state::State (struct) › Example

```
use axum::{Router, routing::get, extract::State};
use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct AppState {
    data: Arc<Mutex<String>>,
}

async fn handler(State(state): State<AppState>) {
    {
        let mut data = state.data.lock().expect("mutex was poisoned");
        *data = "updated foo".to_owned();
    }

    // ...
}

let state = AppState {
    data: Arc::new(Mutex::new("foo".to_owned())),
};

let app = Router::new()
    .route("/", get(handler))
    .with_state(state);
# let _: Router = app;
```

[global]: crate::Router::with_state
[the tokio docs]: https://docs.rs/tokio/1.25.0/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use

## axum::extract::ws::CloseCode (type_alias)

Status code used to indicate why an endpoint is closing the WebSocket connection.

## axum::extract::ws::CloseFrame (struct)

A struct representing the close command.

## axum::extract::ws::DefaultOnFailedUpgrade (struct)

The default `OnFailedUpgrade` used by `WebSocketUpgrade`.

It simply ignores the error.

## axum::extract::ws::Message (enum)

A WebSocket message.

## axum::extract::ws::Message::Binary (variant)

A binary WebSocket message

## axum::extract::ws::Message::Close (variant)

A close message with the optional close frame.

You may "uncleanly" close a WebSocket connection at any time
by simply dropping the [`WebSocket`].
However, you may also use the graceful closing protocol, in which
1. peer A sends a close frame, and does not send any further messages;
2. peer B responds with a close frame, and does not send any further messages;
3. peer A processes the remaining messages sent by peer B, before finally
4. both peers close the connection.

After sending a close frame,
you may still read messages,
but attempts to send another message will error.
After receiving a close frame,
axum will automatically respond with a close frame if necessary
(you do not have to deal with this yourself).
Since no further messages will be received,
you may either do nothing
or explicitly drop the connection.

## axum::extract::ws::Message::Ping (variant)

A ping message with the specified payload

The payload here must have a length less than 125 bytes.

Ping messages will be automatically responded to by the server, so you do not have to worry
about dealing with them yourself.

## axum::extract::ws::Message::Pong (variant)

A pong message with the specified payload

The payload here must have a length less than 125 bytes.

Pong messages will be automatically sent to the client if a ping message is received, so
you do not have to worry about constructing them yourself unless you want to implement a
[unidirectional heartbeat](https://tools.ietf.org/html/rfc6455#section-5.5.3).

## axum::extract::ws::Message::Text (variant)

A text WebSocket message

## axum::extract::ws::OnFailedUpgrade (trait)

What to do when a connection upgrade fails.

See [`WebSocketUpgrade::on_failed_upgrade`] for more details.

## axum::extract::ws::Utf8Bytes (struct)

UTF-8 wrapper for [Bytes].

An [Utf8Bytes] is always guaranteed to contain valid UTF-8.

## axum::extract::ws::WebSocket (struct)

A stream of WebSocket messages.

See [the module level documentation](self) for more details.

## axum::extract::ws::WebSocketUpgrade (struct)

Extractor for establishing WebSocket connections.

For HTTP/1.1 requests, this extractor requires the request method to be `GET`;
in later versions, `CONNECT` is used instead.
To support both, it should be used with [`any`](crate::routing::any).

See the [module docs](self) for an example.

[`MethodFilter`]: crate::routing::MethodFilter

## axum::extract::ws::WebSocketUpgrade::on_failed_upgrade (function)

Provide a callback to call if upgrading the connection fails.

The connection upgrade is performed in a background task. If that fails this callback
will be called.

By default any errors will be silently ignored.

### axum::extract::ws::WebSocketUpgrade::on_failed_upgrade (function) › Example

```
use axum::{
    extract::{WebSocketUpgrade},
    response::Response,
};

async fn handler(ws: WebSocketUpgrade) -> Response {
    ws.on_failed_upgrade(|error| {
        report_error(error);
    })
    .on_upgrade(|socket| async { /* ... */ })
}
#
# fn report_error(_: axum::Error) {}
```

## axum::extract::ws::WebSocketUpgrade::protocols (function)

Set the known protocols.

If the protocol name specified by `Sec-WebSocket-Protocol` header
to match any of them, the upgrade response will include `Sec-WebSocket-Protocol` header and
return the protocol name.

The protocols should be listed in decreasing order of preference: if the client offers
multiple protocols that the server could support, the server will pick the first one in
this list.

### axum::extract::ws::WebSocketUpgrade::protocols (function) › Examples

```
use axum::{
    extract::ws::{WebSocketUpgrade, WebSocket},
    routing::any,
    response::{IntoResponse, Response},
    Router,
};

let app = Router::new().route("/ws", any(handler));

async fn handler(ws: WebSocketUpgrade) -> Response {
    ws.protocols(["graphql-ws", "graphql-transport-ws"])
        .on_upgrade(|socket| async {
            // ...
        })
}
# let _: Router = app;
```

## axum::extract::ws::WebSocketUpgrade::set_selected_protocol (function)

Set the chosen WebSocket subprotocol.

Another method, [`protocols()`][Self::protocols], also sets the chosen WebSocket
subprotocol. If both methods are called, only the latter call takes effect.

### axum::extract::ws::WebSocketUpgrade::set_selected_protocol (function) › Notes

- The chosen protocol is echoed back in the WebSocket upgrade
  response as required by RFC 6455. Some browsers may reject a
  value that was not present in the client's request.

## axum::extract::ws::WebSocketUpgrade::write_buffer_size (function)

The target minimum size of the write buffer to reach before writing the data
to the underlying stream.

The default value is 128 KiB.

If set to `0` each message will be eagerly written to the underlying stream.
It is often more optimal to allow them to buffer a little, hence the default value.

Note: [`flush`](SinkExt::flush) will always fully write the buffer regardless.

## axum::extract::ws::close_code::ABNORMAL (constant)

Indicates an abnormal closure.

## axum::extract::ws::close_code::AGAIN (constant)

Indicates that the server is overloaded and the client should either connect to a different
IP (when multiple targets exist), or reconnect to the same IP when a user has performed an
action.

## axum::extract::ws::close_code::AWAY (constant)

Indicates that an endpoint is "going away", such as a server going down or a browser having
navigated away from a page.

## axum::extract::ws::close_code::ERROR (constant)

Indicates that a server is terminating the connection because it encountered an unexpected
condition that prevented it from fulfilling the request.

## axum::extract::ws::close_code::EXTENSION (constant)

Indicates that an endpoint (client) is terminating the connection because the server
did not respond to extension negotiation correctly.

Specifically, the client has expected the server to negotiate one or more extension(s),
but the server didn't return them in the response message of the WebSocket handshake.
The list of extensions that are needed should be given as the reason for closing.
Note that this status code is not used by the server,
because it can fail the WebSocket handshake instead.

## axum::extract::ws::close_code::INVALID (constant)

Indicates that an endpoint is terminating the connection because it has received data
within a message that was not consistent with the type of the message.

For example, an endpoint received non-UTF-8 RFC3629 data within a text message.

## axum::extract::ws::close_code::NORMAL (constant)

Indicates a normal closure, meaning that the purpose for which the connection was
established has been fulfilled.

## axum::extract::ws::close_code::POLICY (constant)

Indicates that an endpoint is terminating the connection because it has received a message
that violates its policy.

This is a generic status code that can be returned when there is
no other more suitable status code (e.g., `UNSUPPORTED` or `SIZE`) or if there is a need to
hide specific details about the policy.

## axum::extract::ws::close_code::PROTOCOL (constant)

Indicates that an endpoint is terminating the connection due to a protocol error.

## axum::extract::ws::close_code::RESTART (constant)

Indicates that the server is restarting.

## axum::extract::ws::close_code::SIZE (constant)

Indicates that an endpoint is terminating the connection because it has received a message
that is too big for it to process.

## axum::extract::ws::close_code::STATUS (constant)

Indicates that no status code was included in a closing frame.

## axum::extract::ws::close_code::UNSUPPORTED (constant)

Indicates that an endpoint is terminating the connection because it has received a type of
data that it cannot accept.

For example, an endpoint MAY send this if it understands only text data, but receives a binary message.

## axum::extract::ws::rejection::ConnectionNotUpgradable (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

This rejection is returned if the connection cannot be upgraded for example if the
request is HTTP/1.0.

See [MDN] for more details about connection upgrades.

[MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade

## axum::extract::ws::rejection::InvalidConnectionHeader (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

## axum::extract::ws::rejection::InvalidProtocolPseudoheader (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

## axum::extract::ws::rejection::InvalidUpgradeHeader (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

## axum::extract::ws::rejection::InvalidWebSocketVersionHeader (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

## axum::extract::ws::rejection::MethodNotConnect (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

## axum::extract::ws::rejection::MethodNotGet (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

## axum::extract::ws::rejection::WebSocketKeyHeaderMissing (struct)

Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).

## axum::extract::ws::rejection::WebSocketUpgradeRejection (enum)

Rejection used for [`WebSocketUpgrade`](super::WebSocketUpgrade).

Contains one variant for each way the [`WebSocketUpgrade`](super::WebSocketUpgrade)
extractor can fail.

## axum::fallback_service (function)

Add a fallback [`Service`] to the router.

See [`Router::fallback`] for more details.

## axum::fallback_service (function)

Add a fallback service to the router.

This service will be called if no routes matches the incoming request.

```rust
use axum::{
    Router,
    routing::get,
    handler::Handler,
    response::IntoResponse,
    http::{StatusCode, Method, Uri},
};

let handler = get(|| async {}).fallback(fallback);

let app = Router::new().route("/", handler);

async fn fallback(method: Method, uri: Uri) -> (StatusCode, String) {
    (StatusCode::NOT_FOUND, format!("`{method}` not allowed for {uri}"))
}
# let _: Router = app;
```

### axum::fallback_service (function) › When used with `MethodRouter::merge`

Two routers that both have a fallback cannot be merged. Doing so results in a
panic:

```rust,should_panic
use axum::{
    routing::{get, post},
    handler::Handler,
    response::IntoResponse,
    http::{StatusCode, Uri},
};

let one = get(|| async {}).fallback(fallback_one);

let two = post(|| async {}).fallback(fallback_two);

let method_route = one.merge(two);

async fn fallback_one() -> impl IntoResponse { /* ... */ }
async fn fallback_two() -> impl IntoResponse { /* ... */ }
# let app: axum::Router = axum::Router::new().route("/", method_route);
```

### axum::fallback_service (function) › Setting the `Allow` header

By default `MethodRouter` will set the `Allow` header when returning `405 Method
Not Allowed`. This is also done when the fallback is used unless the response
generated by the fallback already sets the `Allow` header.

This means if you use `fallback` to accept additional methods, you should make
sure you set the `Allow` header correctly.

## axum::file_name (function)

The file name found in the
[`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
header.

## axum::form::Form (struct)

URL encoded extractor and response.

### axum::form::Form (struct) › As extractor

If used as an extractor, `Form` will deserialize form data from the request,
specifically:

- If the request has a method of `GET` or `HEAD`, the form data will be read
  from the query string (same as with [`Query`])
- If the request has a different method, the form will be read from the body
  of the request. It must have a `content-type` of
  `application/x-www-form-urlencoded` for this to work. If you want to parse
  `multipart/form-data` request bodies, use [`Multipart`] instead.

This matches how HTML forms are sent by browsers by default.
In both cases, the inner type `T` must implement [`serde::Deserialize`].

⚠️ Since parsing form data might require consuming the request body, the `Form` extractor must be
*last* if there are multiple extractors in a handler. See ["the order of
extractors"][order-of-extractors]

[order-of-extractors]: crate::extract#the-order-of-extractors

```rust
use axum::Form;
use serde::Deserialize;

#[derive(Deserialize)]
struct SignUp {
    username: String,
    password: String,
}

async fn accept_form(Form(sign_up): Form<SignUp>) {
    // ...
}
```

### axum::form::Form (struct) › As response

`Form` can also be used to encode any type that implements
[`serde::Serialize`] as `application/x-www-form-urlencoded`

```rust
use axum::Form;
use serde::Serialize;

#[derive(Serialize)]
struct Payload {
    value: String,
}

async fn handler() -> Form<Payload> {
    Form(Payload { value: "foo".to_owned() })
}
```

[`Query`]: crate::extract::Query
[`Multipart`]: crate::extract::Multipart

## axum::from_bytes (function)

Construct a `Json<T>` from a byte slice. Most users should prefer to use the `FromRequest` impl
but special cases may require first extracting a `Request` into `Bytes` then optionally
constructing a `Json<T>`.

## axum::from_static (function)

Creates from a static str.

## axum::got (struct_field)

The number of actual parameters in the URI.

## axum::handle_error (function)

Apply a [`HandleErrorLayer`].

This is a convenience method for doing `self.layer(HandleErrorLayer::new(f))`.

## axum::handle_error (function)

Convert this service into a [`HandleError`], that will handle errors
by converting them into responses.

 See ["error handling model"] for more details.

[`HandleError`]: crate::error_handling::HandleError
["error handling model"]: crate::error_handling#axums-error-handling-model

## axum::handler::Handler (trait)

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](crate::handler) for more details.

### axum::handler::Handler (trait) › Converting `Handler`s into [`Service`]s

To convert `Handler`s into [`Service`]s 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>,
{}
```
### axum::handler::Handler (trait) › 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:

- Are `async fn`s.
- Take no more than 16 arguments that all implement `Send`.
  - All except the last argument implement [`FromRequestParts`].
  - The last argument implements [`FromRequest`].
- Returns something that implements [`IntoResponse`].
- If a closure is used it must implement `Clone + Send` and be
`'static`.
- Returns a future that is `Send`. The most common way to accidentally make a
future `!Send` is to hold a `!Send` type across an await.

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:

```not_rust
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.

[axum-macros]: https://docs.rs/axum-macros
[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html

### axum::handler::Handler (trait) › 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;
```

### axum::handler::Handler (trait) › About type parameter `T`

**Generally you shouldn't need to worry about `T`**; when calling methods such as
[`post`](crate::routing::method_routing::post) it will be automatically inferred and this is
the intended way for this parameter to be provided in application code.

If you are implementing your own methods that accept implementations of `Handler` as
arguments, then the following may be useful:

The type parameter `T` is a workaround for trait coherence rules, allowing us to
write blanket implementations of `Handler` over many types of handler functions
with different numbers of arguments, without the compiler forbidding us from doing
so because one type `F` can in theory implement both `Fn(A) -> X` and `Fn(A, B) -> Y`.
`T` is a placeholder taking on a representation of the parameters of the handler function,
as well as other similar 'coherence rule workaround' discriminators,
allowing us to select one function signature to use as a `Handler`.

## axum::handler::Handler::layer (function)

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`](crate::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](crate::error_handling).

### axum::handler::Handler::layer (function) › Example

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

```rust
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;
```

## axum::handler::Handler::with_state (function)

Convert the handler into a [`Service`] by providing the state

## axum::handler::HandlerWithoutStateExt (trait)

Extension trait for [`Handler`]s that don't have state.

This provides convenience methods to convert the [`Handler`] into a [`Service`] or [`MakeService`].

[`MakeService`]: tower::make::MakeService

## axum::handler::HandlerWithoutStateExt::into_make_service_with_connect_info (function)

Convert the handler into a [`MakeService`] which stores information
about the incoming connection and has no state.

See [`HandlerService::into_make_service_with_connect_info`] for more details.

[`MakeService`]: tower::make::MakeService

## axum::handler::HandlerWithoutStateExt::into_service (function)

Convert the handler into a [`Service`] and no state.

## axum::handler::Layered (struct)

A [`Service`] created from a [`Handler`] by applying a Tower middleware.

Created with [`Handler::layer`]. See that method for more details.

## axum::handler::future::IntoServiceFuture (struct)

The response future for [`IntoService`](super::IntoService).

## axum::handler::future::LayeredFuture (struct)

The response future for [`Layered`](super::Layered).

## axum::handler::service::HandlerService (struct)

An adapter that makes a [`Handler`] into a [`Service`].

Created with [`Handler::with_state`] or [`HandlerWithoutStateExt::into_service`].

[`HandlerWithoutStateExt::into_service`]: super::HandlerWithoutStateExt::into_service

## axum::handler::service::HandlerService::into_make_service (function)

Convert the handler into a [`MakeService`].

This allows you to serve a single handler if you don't need any routing:

```rust
use axum::{
    handler::Handler,
    extract::State,
    http::{Uri, Method},
    response::IntoResponse,
};
use std::net::SocketAddr;

#[derive(Clone)]
struct AppState {}

async fn handler(State(state): State<AppState>) {
    // ...
}

let app = handler.with_state(AppState {});

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app.into_make_service()).await.unwrap();
# };
```

[`MakeService`]: tower::make::MakeService

## axum::handler::service::HandlerService::into_make_service_with_connect_info (function)

Convert the handler into a [`MakeService`] which stores information
about the incoming connection.

See [`Router::into_make_service_with_connect_info`] for more details.

```rust
use axum::{
    handler::Handler,
    response::IntoResponse,
    extract::{ConnectInfo, State},
};
use std::net::SocketAddr;

#[derive(Clone)]
struct AppState {};

async fn handler(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(state): State<AppState>,
) -> String {
    format!("Hello {addr}")
}

let app = handler.with_state(AppState {});

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(
    listener,
    app.into_make_service_with_connect_info::<SocketAddr>(),
).await.unwrap();
# };
```

[`MakeService`]: tower::make::MakeService
[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info

## axum::head (function)

Chain an additional handler that will only accept `HEAD` requests.

 See [`MethodRouter::get`] for an example.

## axum::head_service (function)

Chain an additional service that will only accept `HEAD` requests.

 See [`MethodRouter::get_service`] for an example.

## axum::headers (function)

Get a map of headers as [`HeaderMap`].

## axum::id (function)

Set the event's identifier field (`id:<identifier>`).

This corresponds to [`MessageEvent`'s `lastEventId` field]. If no ID is in the event itself,
the browser will set that field to the last known message ID, starting with the empty
string.

[`MessageEvent`'s `lastEventId` field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/lastEventId

### axum::id (function) › Panics

- Panics if `id` contains any newlines, carriage returns or null characters.
- Panics if this function has already been called on this event.

## axum::index (struct_field)

The index at which the value was located.

## axum::interval (function)

Customize the interval between keep-alive messages.

Default is 15 seconds.

## axum::into_data (function)

Consume the WebSocket and return it as binary data.

## axum::into_data_writer (function)

Use this [`Event`] as a [`EventDataWriter`] to write custom data.

- [`Self::data`] can be used as a shortcut to write `str` data
- [`Self::json_data`] can be used as a shortcut to write `json` data

Turn it into an [`Event`] again using [`EventDataWriter::into_event`].

## axum::into_make_service (function)

Convert the handler into a [`MakeService`] and no state.

See [`HandlerService::into_make_service`] for more details.

[`MakeService`]: tower::make::MakeService

## axum::into_make_service (function)

Convert the router into a [`MakeService`].

This allows you to serve a single `MethodRouter` if you don't need any
routing based on the path:

```rust
use axum::{
    handler::Handler,
    http::{Uri, Method},
    response::IntoResponse,
    routing::get,
};
use std::net::SocketAddr;

async fn handler(method: Method, uri: Uri, body: String) -> String {
    format!("received `{method} {uri}` with body `{body:?}`")
}

let router = get(handler).post(handler);

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, router.into_make_service()).await.unwrap();
# };
```

[`MakeService`]: tower::make::MakeService

## axum::into_make_service (function)

Convert this service into a [`MakeService`], that is a [`Service`] whose
response is another service.

This is commonly used when applying middleware around an entire [`Router`]. See ["Rewriting
request URI in middleware"] for more details.

[`MakeService`]: tower::make::MakeService
["Rewriting request URI in middleware"]: crate::middleware#rewriting-request-uri-in-middleware
[`Router`]: crate::Router

## axum::into_make_service_with_connect_info (function)

Convert this service into a [`MakeService`], that will store `C`'s
associated `ConnectInfo` in a request extension such that [`ConnectInfo`]
can extract it.

This enables extracting things like the client's remote address.
This is commonly used when applying middleware around an entire [`Router`]. See ["Rewriting
request URI in middleware"] for more details.

[`MakeService`]: tower::make::MakeService
["Rewriting request URI in middleware"]: crate::middleware#rewriting-request-uri-in-middleware
[`Router`]: crate::Router
[`ConnectInfo`]: crate::extract::connect_info::ConnectInfo

## axum::into_map_request_result (function)

Perform the conversion.

## axum::into_text (function)

Attempt to consume the WebSocket message and convert it to a Utf8Bytes.

## axum::io (function)

Get a reference to the inner IO type.

## axum::is_terminated (function)

Returns true if the websocket has been terminated.

## axum::json::Json (struct)

JSON Extractor / Response.

When used as an extractor, it can deserialize request bodies into some type that
implements [`serde::de::DeserializeOwned`]. The request will be rejected (and a [`JsonRejection`] will
be returned) if:

- The request doesn't have a `Content-Type: application/json` (or similar) header.
- The body doesn't contain syntactically valid JSON.
- The body contains syntactically valid JSON, but it couldn't be deserialized into the target type.
- Buffering the request body fails.

⚠️ Since parsing JSON requires consuming the request body, the `Json` extractor must be
*last* if there are multiple extractors in a handler.
See ["the order of extractors"][order-of-extractors]

[order-of-extractors]: crate::extract#the-order-of-extractors

See [`JsonRejection`] for more details.

### axum::json::Json (struct) › Extractor example

```rust,no_run
use axum::{
    extract,
    routing::post,
    Router,
};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}

async fn create_user(extract::Json(payload): extract::Json<CreateUser>) {
    // payload is a `CreateUser`
}

let app = Router::new().route("/users", post(create_user));
# let _: Router = app;
```

When used as a response, it can serialize any type that implements [`serde::Serialize`] to
`JSON`, and will automatically set `Content-Type: application/json` header.

If the [`Serialize`] implementation decides to fail
or if a map with non-string keys is used,
a 500 response will be issued
whose body is the error message in UTF-8.

### axum::json::Json (struct) › Response example

```
use axum::{
    extract::Path,
    routing::get,
    Router,
    Json,
};
use serde::Serialize;
use uuid::Uuid;

#[derive(Serialize)]
struct User {
    id: Uuid,
    username: String,
}

async fn get_user(Path(user_id) : Path<Uuid>) -> Json<User> {
    let user = find_user(user_id).await;
    Json(user)
}

async fn find_user(user_id: Uuid) -> User {
    // ...
    # unimplemented!()
}

let app = Router::new().route("/users/{id}", get(get_user));
# let _: Router = app;
```

## axum::keep_alive (function)

Configure the interval between keep-alive messages.

Defaults to no keep-alive messages.

## axum::key (struct_field)

The key at which the invalid value was located.

## axum::key (struct_field)

The key at which the invalid value was located.

## axum::key (struct_field)

The key at which the value was located.

## axum::local_addr (function)

Returns the local address that this listener is bound to.

## axum::local_addr (function)

Returns the local address this server is bound to.

## axum::local_addr (function)

Returns the local address this server is bound to.

## axum::location (function)

Returns the `Redirect`'s URI.

## axum::max_frame_size (function)

Set the maximum frame size (defaults to 16 megabytes)

## axum::max_message_size (function)

Set the maximum message size (defaults to 64 megabytes)

## axum::max_write_buffer_size (function)

The max size of the write buffer in bytes. Setting this can provide backpressure
in the case the write buffer is filling up due to write errors.

The default value is unlimited.

Note: The write buffer only builds up past [`write_buffer_size`](Self::write_buffer_size)
when writes to the underlying stream are failing. So the **write buffer can not
fill up if you are not observing write errors even if not flushing**.

Note: Should always be at least [`write_buffer_size + 1 message`](Self::write_buffer_size)
and probably a little more depending on error handling strategy.

## axum::merge (function)

Merge two routers into one.

This is useful for breaking routers into smaller pieces and combining them
into one.

```rust
use axum::{
    routing::{get, post},
    Router,
};

let get = get(|| async {});
let post = post(|| async {});

let merged = get.merge(post);

let app = Router::new().route("/", merged);

// Our app now accepts
// - GET /
// - POST /
# let _: Router = app;
```

## axum::message (struct_field)

The deserializaation failure message.

## axum::method_not_allowed_fallback (function)

Add a fallback [`Handler`] for the case where a route exists, but the method of the request is not supported.

Sets a fallback on all previously registered [`MethodRouter`]s,
to be called when no matching method handler is set.

```rust,no_run
use axum::{response::IntoResponse, routing::get, Router};

async fn hello_world() -> impl IntoResponse {
    "Hello, world!\n"
}

async fn default_fallback() -> impl IntoResponse {
    "Default fallback\n"
}

async fn handle_405() -> impl IntoResponse {
    "Method not allowed fallback"
}

#[tokio::main]
async fn main() {
    let router = Router::new()
        .route("/", get(hello_world))
        .fallback(default_fallback)
        .method_not_allowed_fallback(handle_405);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();

    axum::serve(listener, router).await.unwrap();
}
```

The fallback only applies if there is a `MethodRouter` registered for a given path,
but the method used in the request is not specified. In the example, a `GET` on
`http://localhost:3000` causes the `hello_world` handler to react, while issuing a
`POST` triggers `handle_405`. Calling an entirely different route, like `http://localhost:3000/hello`
causes `default_fallback` to run.

## axum::middleware::from_extractor::FromExtractor (struct)

Middleware that runs an extractor and discards the value.

See [`from_extractor`] for more details.

## axum::middleware::from_extractor::FromExtractorLayer (struct)

[`Layer`] that applies [`FromExtractor`] that runs an extractor and
discards the value.

See [`from_extractor`] for more details.

[`Layer`]: tower::Layer

## axum::middleware::from_extractor::ResponseFuture (struct)

Response future for [`FromExtractor`].

## axum::middleware::from_extractor::from_extractor (function)

Create a middleware from an extractor.

If the extractor succeeds the value will be discarded and the inner service
will be called. If the extractor fails the rejection will be returned and
the inner service will _not_ be called.

This can be used to perform validation of requests if the validation doesn't
produce any useful output, and run the extractor for several handlers
without repeating it in the function signature.

Note that if the extractor consumes the request body, as `String` or
[`Bytes`] does, an empty body will be left in its place. Thus won't be
accessible to subsequent extractors or handlers.

### axum::middleware::from_extractor::from_extractor (function) › Example

```rust
use axum::{
    extract::FromRequestParts,
    middleware::from_extractor,
    routing::{get, post},
    Router,
    http::{header, StatusCode, request::Parts},
};

// An extractor that performs authorization.
struct RequireAuth;

impl<S> FromRequestParts<S> for RequireAuth
where
    S: Send + Sync,
{
    type Rejection = StatusCode;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(header::AUTHORIZATION)
            .and_then(|value| value.to_str().ok());

        match auth_header {
            Some(auth_header) if token_is_valid(auth_header) => {
                Ok(Self)
            }
            _ => Err(StatusCode::UNAUTHORIZED),
        }
    }
}

fn token_is_valid(token: &str) -> bool {
    // ...
    # false
}

async fn handler() {
    // If we get here the request has been authorized
}

async fn other_handler() {
    // If we get here the request has been authorized
}

let app = Router::new()
    .route("/", get(handler))
    .route("/foo", post(other_handler))
    // The extractor will run before all routes
    .route_layer(from_extractor::<RequireAuth>());
# let _: Router = app;
```

[`Bytes`]: bytes::Bytes

## axum::middleware::from_extractor::from_extractor_with_state (function)

Create a middleware from an extractor with the given state.

See [`State`](crate::extract::State) for more details about accessing state.

## axum::middleware::from_fn::FromFn (struct)

A middleware created from an async function.

Created with [`from_fn`] or [`from_fn_with_state`]. See those functions for more details.

## axum::middleware::from_fn::FromFnLayer (struct)

A [`tower::Layer`] from an async function.

[`tower::Layer`] is used to apply middleware to [`Router`](crate::Router)'s.

Created with [`from_fn`] or [`from_fn_with_state`]. See those functions for more details.

## axum::middleware::from_fn::Next (struct)

The remainder of a middleware stack, including the handler.

## axum::middleware::from_fn::ResponseFuture (struct)

Response future for [`FromFn`].

## axum::middleware::from_fn::from_fn (function)

Create a middleware from an async function.

`from_fn` requires the function given to

1. Be an `async fn`.
2. Take zero or more [`FromRequestParts`] extractors.
3. Take exactly one [`FromRequest`] extractor as the second to last argument.
4. Take [`Next`](Next) as the last argument.
5. Return something that implements [`IntoResponse`].

Note that this function doesn't support extracting [`State`]. For that, use [`from_fn_with_state`].

### axum::middleware::from_fn::from_fn (function) › Example

```rust
use axum::{
    Router,
    http,
    routing::get,
    response::Response,
    middleware::{self, Next},
    extract::Request,
};

async fn my_middleware(
    request: Request,
    next: Next,
) -> Response {
    // do something with `request`...

    let response = next.run(request).await;

    // do something with `response`...

    response
}

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .layer(middleware::from_fn(my_middleware));
# let app: Router = app;
```

### axum::middleware::from_fn::from_fn (function) › Running extractors

```rust
use axum::{
    Router,
    extract::Request,
    http::{StatusCode, HeaderMap},
    middleware::{self, Next},
    response::Response,
    routing::get,
};

async fn auth(
    // run the `HeaderMap` extractor
    headers: HeaderMap,
    // you can also add more extractors here but the last
    // extractor must implement `FromRequest` which
    // `Request` does
    request: Request,
    next: Next,
) -> Result<Response, StatusCode> {
    match get_token(&headers) {
        Some(token) if token_is_valid(token) => {
            let response = next.run(request).await;
            Ok(response)
        }
        _ => {
            Err(StatusCode::UNAUTHORIZED)
        }
    }
}

fn get_token(headers: &HeaderMap) -> Option<&str> {
    // ...
    # None
}

fn token_is_valid(token: &str) -> bool {
    // ...
    # false
}

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .route_layer(middleware::from_fn(auth));
# let app: Router = app;
```

[extractors]: crate::extract::FromRequest
[`State`]: crate::extract::State

## axum::middleware::from_fn::from_fn_with_state (function)

Create a middleware from an async function with the given state.

For the requirements for the function supplied see [`from_fn`].

See [`State`](crate::extract::State) for more details about accessing state.

### axum::middleware::from_fn::from_fn_with_state (function) › Example

```rust
use axum::{
    Router,
    http::StatusCode,
    routing::get,
    response::{IntoResponse, Response},
    middleware::{self, Next},
    extract::{Request, State},
};

#[derive(Clone)]
struct AppState { /* ... */ }

async fn my_middleware(
    State(state): State<AppState>,
    // you can add more extractors here but the last
    // extractor must implement `FromRequest` which
    // `Request` does
    request: Request,
    next: Next,
) -> Response {
    // do something with `request`...

    let response = next.run(request).await;

    // do something with `response`...

    response
}

let state = AppState { /* ... */ };

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .route_layer(middleware::from_fn_with_state(state.clone(), my_middleware))
    .with_state(state);
# let _: axum::Router = app;
```

## axum::middleware::map_request::IntoMapRequestResult (trait)

Trait implemented by types that can be returned from [`map_request`],
[`map_request_with_state`].

This trait is sealed such that it cannot be implemented outside this crate.

## axum::middleware::map_request::MapRequest (struct)

A middleware created from an async function that transforms a request.

Created with [`map_request`]. See that function for more details.

## axum::middleware::map_request::MapRequestLayer (struct)

A [`tower::Layer`] from an async function that transforms a request.

Created with [`map_request`]. See that function for more details.

## axum::middleware::map_request::ResponseFuture (struct)

Response future for [`MapRequest`].

## axum::middleware::map_request::map_request (function)

Create a middleware from an async function that transforms a request.

This differs from [`tower::util::MapRequest`] in that it allows you to easily run axum-specific
extractors.

### axum::middleware::map_request::map_request (function) › Example

```
use axum::{
    Router,
    routing::get,
    middleware::map_request,
    http::Request,
};

async fn set_header<B>(mut request: Request<B>) -> Request<B> {
    request.headers_mut().insert("x-foo", "foo".parse().unwrap());
    request
}

async fn handler<B>(request: Request<B>) {
    // `request` will have an `x-foo` header
}

let app = Router::new()
    .route("/", get(handler))
    .layer(map_request(set_header));
# let _: Router = app;
```

### axum::middleware::map_request::map_request (function) › Rejecting the request

The function given to `map_request` is allowed to also return a `Result` which can be used to
reject the request and return a response immediately, without calling the remaining
middleware.

Specifically the valid return types are:

- `Request<B>`
- `Result<Request<B>, E> where E:  IntoResponse`

```
use axum::{
    Router,
    http::{Request, StatusCode},
    routing::get,
    middleware::map_request,
};

async fn auth<B>(request: Request<B>) -> Result<Request<B>, StatusCode> {
    let auth_header = request.headers()
        .get(http::header::AUTHORIZATION)
        .and_then(|header| header.to_str().ok());

    match auth_header {
        Some(auth_header) if token_is_valid(auth_header) => Ok(request),
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}

fn token_is_valid(token: &str) -> bool {
    // ...
    # false
}

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .route_layer(map_request(auth));
# let app: Router = app;
```

### axum::middleware::map_request::map_request (function) › Running extractors

```
use axum::{
    Router,
    routing::get,
    middleware::map_request,
    extract::Path,
    http::Request,
};
use std::collections::HashMap;

async fn log_path_params<B>(
    Path(path_params): Path<HashMap<String, String>>,
    request: Request<B>,
) -> Request<B> {
    tracing::debug!(?path_params);
    request
}

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .layer(map_request(log_path_params));
# let _: Router = app;
```

Note that to access state you must use either [`map_request_with_state`].

## axum::middleware::map_request::map_request_with_state (function)

Create a middleware from an async function that transforms a request, with the given state.

See [`State`](crate::extract::State) for more details about accessing state.

### axum::middleware::map_request::map_request_with_state (function) › Example

```rust
use axum::{
    Router,
    http::{Request, StatusCode},
    routing::get,
    response::IntoResponse,
    middleware::map_request_with_state,
    extract::State,
};

#[derive(Clone)]
struct AppState { /* ... */ }

async fn my_middleware<B>(
    State(state): State<AppState>,
    // you can add more extractors here but the last
    // extractor must implement `FromRequest` which
    // `Request` does
    request: Request<B>,
) -> Request<B> {
    // do something with `state` and `request`...
    request
}

let state = AppState { /* ... */ };

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .route_layer(map_request_with_state(state.clone(), my_middleware))
    .with_state(state);
# let _: axum::Router = app;
```

## axum::middleware::map_response::MapResponse (struct)

A middleware created from an async function that transforms a response.

Created with [`map_response`]. See that function for more details.

## axum::middleware::map_response::MapResponseLayer (struct)

A [`tower::Layer`] from an async function that transforms a response.

Created with [`map_response`]. See that function for more details.

## axum::middleware::map_response::ResponseFuture (struct)

Response future for [`MapResponse`].

## axum::middleware::map_response::map_response (function)

Create a middleware from an async function that transforms a response.

This differs from [`tower::util::MapResponse`] in that it allows you to easily run axum-specific
extractors.

### axum::middleware::map_response::map_response (function) › Example

```
use axum::{
    Router,
    routing::get,
    middleware::map_response,
    response::Response,
};

async fn set_header<B>(mut response: Response<B>) -> Response<B> {
    response.headers_mut().insert("x-foo", "foo".parse().unwrap());
    response
}

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .layer(map_response(set_header));
# let _: Router = app;
```

### axum::middleware::map_response::map_response (function) › Running extractors

It is also possible to run extractors that implement [`FromRequestParts`]. These will be run
before calling the handler.

```
use axum::{
    Router,
    routing::get,
    middleware::map_response,
    extract::Path,
    response::Response,
};
use std::collections::HashMap;

async fn log_path_params<B>(
    Path(path_params): Path<HashMap<String, String>>,
    response: Response<B>,
) -> Response<B> {
    tracing::debug!(?path_params);
    response
}

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .layer(map_response(log_path_params));
# let _: Router = app;
```

Note that to access state you must use either [`map_response_with_state`].

### axum::middleware::map_response::map_response (function) › Returning any `impl IntoResponse`

It is also possible to return anything that implements [`IntoResponse`]

```
use axum::{
    Router,
    routing::get,
    middleware::map_response,
    response::{Response, IntoResponse},
};
use std::collections::HashMap;

async fn set_header(response: Response) -> impl IntoResponse {
    (
        [("x-foo", "foo")],
        response,
    )
}

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .layer(map_response(set_header));
# let _: Router = app;
```

## axum::middleware::map_response::map_response_with_state (function)

Create a middleware from an async function that transforms a response, with the given state.

See [`State`](crate::extract::State) for more details about accessing state.

### axum::middleware::map_response::map_response_with_state (function) › Example

```rust
use axum::{
    Router,
    http::StatusCode,
    routing::get,
    response::Response,
    middleware::map_response_with_state,
    extract::State,
};

#[derive(Clone)]
struct AppState { /* ... */ }

async fn my_middleware<B>(
    State(state): State<AppState>,
    // you can add more extractors here but they must
    // all implement `FromRequestParts`
    // `FromRequest` is not allowed
    response: Response<B>,
) -> Response<B> {
    // do something with `state` and `response`...
    response
}

let state = AppState { /* ... */ };

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    .route_layer(map_response_with_state(state.clone(), my_middleware))
    .with_state(state);
# let _: axum::Router = app;
```

## axum::middleware::response_axum_body::ResponseAxumBody (struct)

Service generated by [`ResponseAxumBodyLayer`].

## axum::middleware::response_axum_body::ResponseAxumBodyFuture (struct)

Response future for [`ResponseAxumBody`].

## axum::middleware::response_axum_body::ResponseAxumBodyLayer (struct)

Layer that transforms the Response body to [`crate::body::Body`].

This is useful when another layer maps the body to some other type to convert it back.

## axum::name (function)

The field name found in the
[`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
header.

## axum::name (struct_field)

The name of the unsupported type.

## axum::nest_service (function)

Like [`nest`](Self::nest), but accepts an arbitrary `Service`.

## axum::new (function)

Create a default `MethodRouter` that will respond with `405 Method Not Allowed` to all
requests.

## axum::new (function)

Create a new [`Sse`] response that will respond with the given stream of
[`Event`]s.

See the [module docs](self) for more details.

## axum::new (function)

Create a new `HandleErrorLayer`.

## axum::new (function)

Create a new `HandleError`.

## axum::new (function)

Create a new `KeepAlive`.

## axum::new (function)

Create a new `Router`.

Unless you add additional routes this will respond with `404 Not Found` to
all requests.

## axum::next_field (function)

Yields the next [`Field`] if available.

## axum::on (function)

Chain an additional handler that will accept requests matching the given
`MethodFilter`.

### axum::on (function) › Example

```rust
use axum::{
    routing::get,
    Router,
    routing::MethodFilter
};

async fn handler() {}

async fn other_handler() {}

// Requests to `GET /` will go to `handler` and `DELETE /` will go to
// `other_handler`
let app = Router::new().route("/", get(handler).on(MethodFilter::DELETE, other_handler));
# let _: Router = app;
```

## axum::on_service (function)

Chain an additional service that will accept requests matching the given
`MethodFilter`.

### axum::on_service (function) › Example

```rust
use axum::{
    extract::Request,
    Router,
    routing::{MethodFilter, on_service},
    body::Body,
};
use http::Response;
use std::convert::Infallible;

let service = tower::service_fn(|request: Request| async {
    Ok::<_, Infallible>(Response::new(Body::empty()))
});

// Requests to `DELETE /` will go to `service`
let app = Router::new().route("/", on_service(MethodFilter::DELETE, service));
# let _: Router = app;
```

## axum::on_upgrade (function)

Finalize upgrading the connection and call the provided callback with
the stream.

## axum::options (function)

Chain an additional handler that will only accept `OPTIONS` requests.

 See [`MethodRouter::get`] for an example.

## axum::options_service (function)

Chain an additional service that will only accept `OPTIONS` requests.

 See [`MethodRouter::get_service`] for an example.

## axum::or (function)

Performs the OR operation between the [`MethodFilter`] in `self` with `other`.

## axum::patch (function)

Chain an additional handler that will only accept `PATCH` requests.

 See [`MethodRouter::get`] for an example.

## axum::patch_service (function)

Chain an additional service that will only accept `PATCH` requests.

 See [`MethodRouter::get_service`] for an example.

## axum::permanent (function)

Create a new [`Redirect`] that uses a [`308 Permanent Redirect`][mdn] status code.

[mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308

## axum::post (function)

Chain an additional handler that will only accept `POST` requests.

 See [`MethodRouter::get`] for an example.

## axum::post_service (function)

Chain an additional service that will only accept `POST` requests.

 See [`MethodRouter::get_service`] for an example.

## axum::protocol (function)

Return the selected WebSocket subprotocol, if one has been chosen.

## axum::put (function)

Chain an additional handler that will only accept `PUT` requests.

 See [`MethodRouter::get`] for an example.

## axum::put_service (function)

Chain an additional service that will only accept `PUT` requests.

 See [`MethodRouter::get_service`] for an example.

## axum::read_buffer_size (function)

Read buffer capacity. The default value is 128KiB

## axum::reason (struct_field)

The reason as text string.

## axum::recv (function)

Receive another message.

Returns `None` if the stream has closed.

## axum::remote_addr (function)

Returns the remote address that this stream is bound to.

## axum::requested_protocols (function)

Return the WebSocket subprotocols requested by the client.

### axum::requested_protocols (function) › Examples

If the client sends the following HTTP header in the WebSocket upgrade request:

```txt
Sec-WebSocket-Protocol: soap, wamp
```

this method returns an iterator yielding `"soap"` and `"wamp"`.

## axum::reset_fallback (function)

Reset the fallback to its default.

Useful to merge two routers with fallbacks, as [`merge`] doesn't allow
both routers to have an explicit fallback. Use this method to remove the
one you want to discard before merging.

[`merge`]: Self::merge

## axum::response::Html (struct)

An HTML response.

Will automatically get `Content-Type: text/html`.

## axum::response::NoContent (struct)

An empty response with 204 No Content status.

Due to historical and implementation reasons, the `IntoResponse` implementation of `()`
(unit type) returns an empty response with 200 [`StatusCode::OK`] status.
If you specifically want a 204 [`StatusCode::NO_CONTENT`] status, you can use either `StatusCode` type
directly, or this shortcut struct for self-documentation.

```
use axum::{extract::Path, response::NoContent};

async fn delete_user(Path(user): Path<String>) -> Result<NoContent, String> {
    // ...access database...
# drop(user);
    Ok(NoContent)
}
```

## axum::response::redirect::Redirect (struct)

Response that redirects the request to another location.

### axum::response::redirect::Redirect (struct) › Example

```rust
use axum::{
    routing::get,
    response::Redirect,
    Router,
};

let app = Router::new()
    .route("/old", get(|| async { Redirect::permanent("/new") }))
    .route("/new", get(|| async { "Hello!" }));
# let _: Router = app;
```

## axum::response::redirect::Redirect::temporary (function)

Create a new [`Redirect`] that uses a [`307 Temporary Redirect`][mdn] status code.

This has the same behavior as [`Redirect::to`], except it will preserve the original HTTP
method and body.

[mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307

## axum::response::redirect::Redirect::to (function)

Create a new [`Redirect`] that uses a [`303 See Other`][mdn] status code.

This redirect instructs the client to change the method to GET for the subsequent request
to the given `uri`, which is useful after successful form submission, file upload or when
you generally don't want the redirected-to page to observe the original request method and
body (if non-empty). If you want to preserve the request method and body,
[`Redirect::temporary`] should be used instead.

[mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303

## axum::response::sse::Event (struct)

Server-sent event

## axum::response::sse::Event::data (function)

Set the event's data data field(s) (`data: <content>`)

Newlines in `data` will automatically be broken across `data: ` fields.

This corresponds to [`MessageEvent`'s data field].

Note that events with an empty data field will be ignored by the browser.

### axum::response::sse::Event::data (function) › Panics

Panics if any `data` has already been written before.

[`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data

## axum::response::sse::Event::json_data (function)

Set the event's data field to a value serialized as unformatted JSON (`data: <content>`).

This corresponds to [`MessageEvent`'s data field].

### axum::response::sse::Event::json_data (function) › Panics

Panics if any `data` has already been written before.

[`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data

## axum::response::sse::EventDataWriter (struct)

Expose [`Event`] as a [`std::fmt::Write`]
such that any form of data can be written as data safely.

This also ensures that newline characters `\r` and `\n`
correctly trigger a split with a new `data: ` prefix.

### axum::response::sse::EventDataWriter (struct) › Panics

Panics if any `data` has already been written prior to the first write
of this [`EventDataWriter`] instance.

## axum::response::sse::EventDataWriter::into_event (function)

Consume the [`EventDataWriter`] and return the [`Event`] once again.

In case any data was written by this instance
it will also write the trailing `\n` character.

## axum::response::sse::KeepAlive (struct)

Configure the interval between keep-alive messages, the content
of each message, and the associated stream.

## axum::response::sse::KeepAliveStream (struct)

A wrapper around a stream that produces keep-alive events

## axum::response::sse::Sse (struct)

An SSE response

## axum::retry (function)

Set the event's retry timeout field (`retry: <timeout>`).

This sets how long clients will wait before reconnecting if they are disconnected from the
SSE endpoint. Note that this is just a hint: clients are free to wait for longer if they
wish, such as if they implement exponential backoff.

### axum::retry (function) › Panics

Panics if this function has already been called on this event.

## axum::route_service (function)

Add another route to the router that calls a [`Service`].

### axum::route_service (function) › Example

```rust,no_run
use axum::{
    Router,
    body::Body,
    routing::{any_service, get_service},
    extract::Request,
    http::StatusCode,
    error_handling::HandleErrorLayer,
};
use tower_http::services::ServeFile;
use http::Response;
use std::{convert::Infallible, io};
use tower::service_fn;

let app = Router::new()
    .route(
        // Any request to `/` goes to a service
        "/",
        // Services whose response body is not `axum::body::BoxBody`
        // can be wrapped in `axum::routing::any_service` (or one of the other routing filters)
        // to have the response body mapped
        any_service(service_fn(|_: Request| async {
            let res = Response::new(Body::from("Hi from `GET /`"));
            Ok::<_, Infallible>(res)
        }))
    )
    .route_service(
        "/foo",
        // This service's response body is `axum::body::BoxBody` so
        // it can be routed to directly.
        service_fn(|req: Request| async move {
            let body = Body::from(format!("Hi from `{} /foo`", req.method()));
            let res = Response::new(body);
            Ok::<_, Infallible>(res)
        })
    )
    .route_service(
        // GET `/static/Cargo.toml` goes to a service from tower-http
        "/static/Cargo.toml",
        ServeFile::new("Cargo.toml"),
    );
# let _: Router = app;
```

Routing to arbitrary services in this way has complications for backpressure
([`Service::poll_ready`]). See the [Routing to services and backpressure] module
for more details.

### axum::route_service (function) › Panics

Panics for the same reasons as [`Router::route`] or if you attempt to route to a
`Router`:

```rust,should_panic
use axum::{routing::get, Router};

let app = Router::new().route_service(
    "/",
    Router::new().route("/foo", get(|| async {})),
);
# let _: Router = app;
```

Use [`Router::nest`] instead.

[Routing to services and backpressure]: middleware/index.html#routing-to-servicesmiddleware-and-backpressure

## axum::routing::Router (struct)

The router type for composing handlers and services.

`Router<S>` means a router that is _missing_ a state of type `S` to be able
to handle requests. Thus, only `Router<()>` (i.e. without missing state) can
be passed to [`serve`]. See [`Router::with_state`] for more details.

[`serve`]: crate::serve()

## axum::routing::Router::as_service (function)

Convert the router into a borrowed [`Service`] with a fixed request body type, to aid type
inference.

In some cases when calling methods from [`tower::ServiceExt`] on a [`Router`] you might get
type inference errors along the lines of

```not_rust
let response = router.ready().await?.call(request).await?;
                      ^^^^^ cannot infer type for type parameter `B`
```

This happens because `Router` implements [`Service`] with `impl<B> Service<Request<B>> for Router<()>`.

For example:

```compile_fail
use axum::{
    Router,
    routing::get,
    http::Request,
    body::Body,
};
use tower::{Service, ServiceExt};

# async fn async_main() -> Result<(), Box<dyn std::error::Error>> {
let mut router = Router::new().route("/", get(|| async {}));
let request = Request::new(Body::empty());
let response = router.ready().await?.call(request).await?;
# Ok(())
# }
```

Calling `Router::as_service` fixes that:

```
use axum::{
    Router,
    routing::get,
    http::Request,
    body::Body,
};
use tower::{Service, ServiceExt};

# async fn async_main() -> Result<(), Box<dyn std::error::Error>> {
let mut router = Router::new().route("/", get(|| async {}));
let request = Request::new(Body::empty());
let response = router.as_service().ready().await?.call(request).await?;
# Ok(())
# }
```

This is mainly used when calling `Router` in tests. It shouldn't be necessary when running
the `Router` normally via [`Router::into_make_service`].

## axum::routing::Router::fallback (function)

Add a fallback [`Handler`] to the router.

This service will be called if no routes matches the incoming request.

```rust
use axum::{
    Router,
    routing::get,
    handler::Handler,
    response::IntoResponse,
    http::{StatusCode, Uri},
};

let app = Router::new()
    .route("/foo", get(|| async { /* ... */ }))
    .fallback(fallback);

async fn fallback(uri: Uri) -> (StatusCode, String) {
    (StatusCode::NOT_FOUND, format!("No route for {uri}"))
}
# let _: Router = app;
```

Fallbacks only apply to routes that aren't matched by anything in the
router. If a handler is matched by a request but returns 404 the
fallback is not called. Note that this applies to [`MethodRouter`]s too: if the
request hits a valid path but the [`MethodRouter`] does not have an appropriate
method handler installed, the fallback is not called (use
[`MethodRouter::fallback`] for this purpose instead).


### axum::routing::Router::fallback (function) › Handling all requests without other routes

Using `Router::new().fallback(...)` to accept all request regardless of path or
method, if you don't have other routes, isn't optimal:

```rust
use axum::Router;

async fn handler() {}

let app = Router::new().fallback(handler);

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
# };
```

Running the handler directly is faster since it avoids the overhead of routing:

```rust
use axum::handler::HandlerWithoutStateExt;

async fn handler() {}

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, handler.into_make_service()).await.unwrap();
# };
```

## axum::routing::Router::has_routes (function)

True if the router currently has at least one route added.

## axum::routing::Router::into_make_service (function)

Convert this router into a [`MakeService`], that is a [`Service`] whose
response is another service.

```
use axum::{
    routing::get,
    Router,
};

let app = Router::new().route("/", get(|| async { "Hi!" }));

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
# };
```

[`MakeService`]: tower::make::MakeService

## axum::routing::Router::into_make_service_with_connect_info (function)

Convert this router into a [`MakeService`], that will store `C`'s
associated `ConnectInfo` in a request extension such that [`ConnectInfo`]
can extract it.

This enables extracting things like the client's remote address.

Extracting [`std::net::SocketAddr`] is supported out of the box:

```rust
use axum::{
    extract::ConnectInfo,
    routing::get,
    Router,
};
use std::net::SocketAddr;

let app = Router::new().route("/", get(handler));

async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
    format!("Hello {addr}")
}

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();
# };
```

You can implement custom a [`Connected`] like so:

```rust
use axum::{
    extract::connect_info::{ConnectInfo, Connected},
    routing::get,
    serve::IncomingStream,
    Router,
};
use tokio::net::TcpListener;

let app = Router::new().route("/", get(handler));

async fn handler(
    ConnectInfo(my_connect_info): ConnectInfo<MyConnectInfo>,
) -> String {
    format!("Hello {my_connect_info:?}")
}

#[derive(Clone, Debug)]
struct MyConnectInfo {
    // ...
}

impl Connected<IncomingStream<'_, TcpListener>> for MyConnectInfo {
    fn connect_info(target: IncomingStream<'_, TcpListener>) -> Self {
        MyConnectInfo {
            // ...
        }
    }
}

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app.into_make_service_with_connect_info::<MyConnectInfo>()).await.unwrap();
# };
```

See the [unix domain socket example][uds] for an example of how to use
this to collect UDS connection info.

[`MakeService`]: tower::make::MakeService
[`Connected`]: crate::extract::connect_info::Connected
[`ConnectInfo`]: crate::extract::connect_info::ConnectInfo
[uds]: https://github.com/tokio-rs/axum/blob/main/examples/unix-domain-socket/src/main.rs

## axum::routing::Router::into_service (function)

Convert the router into an owned [`Service`] with a fixed request body type, to aid type
inference.

This is the same as [`Router::as_service`] instead it returns an owned [`Service`]. See
that method for more details.

## axum::routing::Router::layer (function)

Apply a [`tower::Layer`] to all routes in the router.

This can be used to add additional processing to a request for a group
of routes.

Note that the middleware is only applied to existing routes. So you have to
first add your routes (and / or fallback) and then call `layer` afterwards. Additional
routes added after `layer` is called will not have the middleware added.

If you want to add middleware to a single handler you can either use
[`MethodRouter::layer`] or [`Handler::layer`].

### axum::routing::Router::layer (function) › Example

Adding the [`tower_http::trace::TraceLayer`]:

```rust
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;

let app = Router::new()
    .route("/foo", get(|| async {}))
    .route("/bar", get(|| async {}))
    .layer(TraceLayer::new_for_http());
# let _: Router = app;
```

If you need to write your own middleware see ["Writing
middleware"](crate::middleware#writing-middleware) for the different options.

If you only want middleware on some routes you can use [`Router::merge`]:

```rust
use axum::{routing::get, Router};
use tower_http::{trace::TraceLayer, compression::CompressionLayer};

let with_tracing = Router::new()
    .route("/foo", get(|| async {}))
    .layer(TraceLayer::new_for_http());

let with_compression = Router::new()
    .route("/bar", get(|| async {}))
    .layer(CompressionLayer::new());

// Merge everything into one `Router`
let app = Router::new()
    .merge(with_tracing)
    .merge(with_compression);
# let _: Router = app;
```

### axum::routing::Router::layer (function) › Multiple middleware

It's recommended to use [`tower::ServiceBuilder`] when applying multiple
middleware. See [`middleware`](crate::middleware) for more details.

### axum::routing::Router::layer (function) › Runs after routing

Middleware added with this method will run _after_ routing and thus cannot be
used to rewrite the request URI. See ["Rewriting request URI in
middleware"](crate::middleware#rewriting-request-uri-in-middleware) for more
details and a workaround.

### axum::routing::Router::layer (function) › Error handling

See [`middleware`](crate::middleware) for details on how error handling impacts
middleware.

## axum::routing::Router::merge (function)

Merge the paths and fallbacks of two routers into a single [`Router`].

This is useful for breaking apps into smaller pieces and combining them
into one.

```rust
use axum::{
    routing::get,
    Router,
};
#
# async fn users_list() {}
# async fn users_show() {}
# async fn teams_list() {}

// define some routes separately
let user_routes = Router::new()
    .route("/users", get(users_list))
    .route("/users/{id}", get(users_show));

let team_routes = Router::new()
    .route("/teams", get(teams_list));

// combine them into one
let app = Router::new()
    .merge(user_routes)
    .merge(team_routes);

// could also do `user_routes.merge(team_routes)`

// Our app now accepts
// - GET /users
// - GET /users/{id}
// - GET /teams
# let _: Router = app;
```

### axum::routing::Router::merge (function) › Merging routers with state

When combining [`Router`]s with this method, each [`Router`] must have the
same type of state. If your routers have different types you can use
[`Router::with_state`] to provide the state and make the types match:

```rust
use axum::{
    Router,
    routing::get,
    extract::State,
};

#[derive(Clone)]
struct InnerState {}

#[derive(Clone)]
struct OuterState {}

async fn inner_handler(state: State<InnerState>) {}

let inner_router = Router::new()
    .route("/bar", get(inner_handler))
    .with_state(InnerState {});

async fn outer_handler(state: State<OuterState>) {}

let app = Router::new()
    .route("/", get(outer_handler))
    .merge(inner_router)
    .with_state(OuterState {});
# let _: axum::Router = app;
```

### axum::routing::Router::merge (function) › Merging routers with fallbacks

When combining [`Router`]s with this method, the [fallback](Router::fallback) is also merged.
However only one of the routers can have a fallback.

### axum::routing::Router::merge (function) › Panics

- If two routers that each have a [fallback](Router::fallback) are merged. This
  is because `Router` only allows a single fallback.

## axum::routing::Router::nest (function)

Nest a [`Router`] at some path.

This allows you to break your application into smaller pieces and compose
them together.

### axum::routing::Router::nest (function) › Example

```rust
use axum::{
    routing::{get, post},
    Router,
};

let user_routes = Router::new().route("/{id}", get(|| async {}));

let team_routes = Router::new().route("/", post(|| async {}));

let api_routes = Router::new()
    .nest("/users", user_routes)
    .nest("/teams", team_routes);

let app = Router::new().nest("/api", api_routes);

// Our app now accepts
// - GET /api/users/{id}
// - POST /api/teams
# let _: Router = app;
```

### axum::routing::Router::nest (function) › How the URI changes

Note that nested routes will not see the original request URI but instead
have the matched prefix stripped. This is necessary for services like static
file serving to work. Use [`OriginalUri`] if you need the original request
URI.

### axum::routing::Router::nest (function) › Captures from outer routes

Take care when using `nest` together with dynamic routes as nesting also
captures from the outer routes:

```rust
use axum::{
    extract::Path,
    routing::get,
    Router,
};
use std::collections::HashMap;

async fn users_get(Path(params): Path<HashMap<String, String>>) {
    // Both `version` and `id` were captured even though `users_api` only
    // explicitly captures `id`.
    let version = params.get("version");
    let id = params.get("id");
}

let users_api = Router::new().route("/users/{id}", get(users_get));

let app = Router::new().nest("/{version}/api", users_api);
# let _: Router = app;
```

### axum::routing::Router::nest (function) › Differences from wildcard routes

Nested routes are similar to wildcard routes. The difference is that
wildcard routes still see the whole URI whereas nested routes will have
the prefix stripped:

```rust
use axum::{routing::get, http::Uri, Router};

let nested_router = Router::new()
    .route("/", get(|uri: Uri| async {
        // `uri` will _not_ contain `/bar`
    }));

let app = Router::new()
    .route("/foo/{*rest}", get(|uri: Uri| async {
        // `uri` will contain `/foo`
    }))
    .nest("/bar", nested_router);
# let _: Router = app;
```

Additionally, while the wildcard route `/foo/*rest` will not match the
paths `/foo` or `/foo/`, a nested router at `/foo` will match the path `/foo`
(but not `/foo/`), and a nested router at `/foo/` will match the path `/foo/`
(but not `/foo`).

### axum::routing::Router::nest (function) › Fallbacks

If a nested router doesn't have its own fallback then it will inherit the
fallback from the outer router:

```rust
use axum::{routing::get, http::StatusCode, handler::Handler, Router};

async fn fallback() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "Not Found")
}

let api_routes = Router::new().route("/users", get(|| async {}));

let app = Router::new()
    .nest("/api", api_routes)
    .fallback(fallback);
# let _: Router = app;
```

Here requests like `GET /api/not-found` will go into `api_routes` but because
it doesn't have a matching route and doesn't have its own fallback it will call
the fallback from the outer router, i.e. the `fallback` function.

If the nested router has its own fallback then the outer fallback will not be
inherited:

```rust
use axum::{
    routing::get,
    http::StatusCode,
    handler::Handler,
    Json,
    Router,
};

async fn fallback() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "Not Found")
}

async fn api_fallback() -> (StatusCode, Json<serde_json::Value>) {
    (
        StatusCode::NOT_FOUND,
        Json(serde_json::json!({ "status": "Not Found" })),
    )
}

let api_routes = Router::new()
    .route("/users", get(|| async {}))
    .fallback(api_fallback);

let app = Router::new()
    .nest("/api", api_routes)
    .fallback(fallback);
# let _: Router = app;
```

Here requests like `GET /api/not-found` will go to `api_fallback`.

### axum::routing::Router::nest (function) › Nesting routers with state

When combining [`Router`]s with this method, each [`Router`] must have the
same type of state. If your routers have different types you can use
[`Router::with_state`] to provide the state and make the types match:

```rust
use axum::{
    Router,
    routing::get,
    extract::State,
};

#[derive(Clone)]
struct InnerState {}

#[derive(Clone)]
struct OuterState {}

async fn inner_handler(state: State<InnerState>) {}

let inner_router = Router::new()
    .route("/bar", get(inner_handler))
    .with_state(InnerState {});

async fn outer_handler(state: State<OuterState>) {}

let app = Router::new()
    .route("/", get(outer_handler))
    .nest("/foo", inner_router)
    .with_state(OuterState {});
# let _: axum::Router = app;
```

Note that the inner router will still inherit the fallback from the outer
router.

### axum::routing::Router::nest (function) › Panics

- If the route overlaps with another route. See [`Router::route`]
  for more details.
- If the route contains a wildcard (`*`).
- If `path` is empty.

[`OriginalUri`]: crate::extract::OriginalUri
[fallbacks]: Router::fallback

## axum::routing::Router::route (function)

Add another route to the router.

`path` is a string of path segments separated by `/`. Each segment
can be either static, a capture, or a wildcard.

`method_router` is the [`MethodRouter`] that should receive the request if the
path matches `path`. Usually, `method_router` will be a handler wrapped in a method
router like [`get`]. See [`handler`](crate::handler) for more details on handlers.

### axum::routing::Router::route (function) › Static paths

Examples:

- `/`
- `/foo`
- `/users/123`

If the incoming request matches the path exactly the corresponding service will
be called.

### axum::routing::Router::route (function) › Captures

Paths can contain segments like `/{key}` which matches any single segment and
will store the value captured at `key`. The value captured can be zero-length
except for in the invalid path `//`.

Examples:

- `/{key}`
- `/users/{id}`
- `/users/{id}/tweets`

Captures can be extracted using [`Path`](crate::extract::Path). See its
documentation for more details.

It is not possible to create segments that only match some types like numbers or
regular expression. You must handle that manually in your handlers.

[`MatchedPath`](crate::extract::MatchedPath) can be used to extract the matched
path rather than the actual path.

### axum::routing::Router::route (function) › Wildcards

Paths can end in `/{*key}` which matches all segments and will store the segments
captured at `key`.

Examples:

- `/{*key}`
- `/assets/{*path}`
- `/{id}/{repo}/{*tree}`

Note that `/{*key}` doesn't match empty segments. Thus:

- `/{*key}` doesn't match `/` but does match `/a`, `/a/`, etc.
- `/x/{*key}` doesn't match `/x` or `/x/` but does match `/x/a`, `/x/a/`, etc.

Wildcard captures can also be extracted using [`Path`](crate::extract::Path):

```rust
use axum::{
    Router,
    routing::get,
    extract::Path,
};

let app: Router = Router::new().route("/{*key}", get(handler));

async fn handler(Path(path): Path<String>) -> String {
    path
}
```

Note that the leading slash is not included, i.e. for the route `/foo/{*rest}` and
the path `/foo/bar/baz` the value of `rest` will be `bar/baz`.

### axum::routing::Router::route (function) › Accepting multiple methods

To accept multiple methods for the same route you can add all handlers at the
same time:

```rust
use axum::{Router, routing::{get, delete}, extract::Path};

let app = Router::new().route(
    "/",
    get(get_root).post(post_root).delete(delete_root),
);

async fn get_root() {}

async fn post_root() {}

async fn delete_root() {}
# let _: Router = app;
```

Or you can add them one by one:

```rust
# use axum::Router;
# use axum::routing::{get, post, delete};
#
let app = Router::new()
    .route("/", get(get_root))
    .route("/", post(post_root))
    .route("/", delete(delete_root));
#
# let _: Router = app;
# async fn get_root() {}
# async fn post_root() {}
# async fn delete_root() {}
```

### axum::routing::Router::route (function) › More examples

```rust
use axum::{Router, routing::{get, delete}, extract::Path};

let app = Router::new()
    .route("/", get(root))
    .route("/users", get(list_users).post(create_user))
    .route("/users/{id}", get(show_user))
    .route("/api/{version}/users/{id}/action", delete(do_users_action))
    .route("/assets/{*path}", get(serve_asset));

async fn root() {}

async fn list_users() {}

async fn create_user() {}

async fn show_user(Path(id): Path<u64>) {}

async fn do_users_action(Path((version, id)): Path<(String, u64)>) {}

async fn serve_asset(Path(path): Path<String>) {}
# let _: Router = app;
```

### axum::routing::Router::route (function) › Panics

Panics if the route overlaps with another route:

```rust,should_panic
use axum::{routing::get, Router};

let app = Router::new()
    .route("/", get(|| async {}))
    .route("/", get(|| async {}));
# let _: Router = app;
```

The static route `/foo` and the dynamic route `/{key}` are not considered to
overlap and `/foo` will take precedence.

Also panics if `path` is empty.

## axum::routing::Router::route_layer (function)

Apply a [`tower::Layer`] to the router that will only run if the request matches
a route.

Note that the middleware is only applied to existing routes. So you have to
first add your routes (and / or fallback) and then call `route_layer`
afterwards. Additional routes added after `route_layer` is called will not have
the middleware added.

This works similarly to [`Router::layer`] except the middleware will only run if
the request matches a route. This is useful for middleware that return early
(such as authorization) which might otherwise convert a `404 Not Found` into a
`401 Unauthorized`.

This function will panic if no routes have been declared yet on the router,
since the new layer will have no effect, and this is typically a bug.
In generic code, you can test if that is the case first, by calling [`Router::has_routes`].

### axum::routing::Router::route_layer (function) › Example

```rust
use axum::{
    routing::get,
    Router,
};
use tower_http::validate_request::ValidateRequestHeaderLayer;

let app = Router::new()
    .route("/foo", get(|| async {}))
    .route_layer(ValidateRequestHeaderLayer::bearer("password"));

// `GET /foo` with a valid token will receive `200 OK`
// `GET /foo` with a invalid token will receive `401 Unauthorized`
// `GET /not-found` with a invalid token will receive `404 Not Found`
# let _: Router = app;
```

## axum::routing::Router::with_state (function)

Provide the state for the router. State passed to this method is global and will be used
for all requests this router receives. That means it is not suitable for holding state derived from a request, such as authorization data extracted in a middleware. Use [`Extension`] instead for such data.

See ["Sharing state with handlers"][sharing-state] for an overview of state patterns,
including when to use `Arc`, how to extract substates with [`FromRef`], and what the
`Router<S>` type parameter means.

[sharing-state]: crate#sharing-state-with-handlers
[`FromRef`]: crate::extract::FromRef

```rust
use axum::{Router, routing::get, extract::State};

#[derive(Clone)]
struct AppState {}

let routes = Router::new()
    .route("/", get(|State(state): State<AppState>| async {
        // use state
    }))
    .with_state(AppState {});

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, routes).await.unwrap();
# };
```

### axum::routing::Router::with_state (function) › Returning routers with states from functions

When returning `Router`s from functions, it is generally recommended not to set the
state directly:

```rust
use axum::{Router, routing::get, extract::State};

#[derive(Clone)]
struct AppState {}

// Don't call `Router::with_state` here
fn routes() -> Router<AppState> {
    Router::new()
        .route("/", get(|_: State<AppState>| async {}))
}

// Instead do it before you run the server
let routes = routes().with_state(AppState {});

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, routes).await.unwrap();
# };
```

If you do need to provide the state, and you're _not_ nesting/merging the router
into another router, then return `Router` without any type parameters:

```rust
# use axum::{Router, routing::get, extract::State};
# #[derive(Clone)]
# struct AppState {}
#
// Don't return `Router<AppState>`
fn routes(state: AppState) -> Router {
    Router::new()
        .route("/", get(|_: State<AppState>| async {}))
        .with_state(state)
}

let routes = routes(AppState {});

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, routes).await.unwrap();
# };
```

This is because we can only call `Router::into_make_service` on `Router<()>`,
not `Router<AppState>`. See below for more details about why that is.

Note that the state defaults to `()` so `Router` and `Router<()>` is the same.

If you are nesting/merging the router it is recommended to use a generic state
type on the resulting router:

```rust
# use axum::{Router, routing::get, extract::State};
# #[derive(Clone)]
# struct AppState {}
#
fn routes<S>(state: AppState) -> Router<S> {
    Router::new()
        .route("/", get(|_: State<AppState>| async {}))
        .with_state(state)
}

let routes = Router::new().nest("/api", routes(AppState {}));

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, routes).await.unwrap();
# };
```

### axum::routing::Router::with_state (function) › What `S` in `Router<S>` means

`Router<S>` means a router that is _missing_ a state of type `S` to be able to
handle requests. It does _not_ mean a `Router` that _has_ a state of type `S`.

For example:

```rust
# use axum::{Router, routing::get, extract::State};
# #[derive(Clone)]
# struct AppState {}
#
// A router that _needs_ an `AppState` to handle requests
let router: Router<AppState> = Router::new()
    .route("/", get(|_: State<AppState>| async {}));

// Once we call `Router::with_state` the router isn't missing
// the state anymore, because we just provided it
//
// Therefore the router type becomes `Router<()>`, i.e a router
// that is not missing any state
let router: Router<()> = router.with_state(AppState {});

// Only `Router<()>` has the `into_make_service` method.
//
// You cannot call `into_make_service` on a `Router<AppState>`
// because it is still missing an `AppState`.
# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, router).await.unwrap();
# };
```

Perhaps a little counter intuitively, `Router::with_state` doesn't always return a
`Router<()>`. Instead you get to pick what the new missing state type is:

```rust
# use axum::{Router, routing::get, extract::State};
# #[derive(Clone)]
# struct AppState {}
#
let router: Router<AppState> = Router::new()
    .route("/", get(|_: State<AppState>| async {}));

// When we call `with_state` we're able to pick what the next missing state type is.
// Here we pick `String`.
let string_router: Router<String> = router.with_state(AppState {});

// That allows us to add new routes that uses `String` as the state type
let string_router = string_router
    .route("/needs-string", get(|_: State<String>| async {}));

// Provide the `String` and choose `()` as the new missing state.
let final_router: Router<()> = string_router.with_state("foo".to_owned());

// Since we have a `Router<()>` we can run it.
# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, final_router).await.unwrap();
# };
```

This is why returning `Router<AppState>` after calling `with_state` doesn't
work:

```rust,compile_fail
# use axum::{Router, routing::get, extract::State};
# #[derive(Clone)]
# struct AppState {}
#
// This won't work because we're returning a `Router<AppState>`
// i.e. we're saying we're still missing an `AppState`
fn routes(state: AppState) -> Router<AppState> {
    Router::new()
        .route("/", get(|_: State<AppState>| async {}))
        .with_state(state)
}

let app = routes(AppState {});

// We can only call `Router::into_make_service` on a `Router<()>`
// but `app` is a `Router<AppState>`
# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
# };
```

Instead return `Router<()>` since we have provided all the state needed:

```rust
# use axum::{Router, routing::get, extract::State};
# #[derive(Clone)]
# struct AppState {}
#
// We've provided all the state necessary so return `Router<()>`
fn routes(state: AppState) -> Router<()> {
    Router::new()
        .route("/", get(|_: State<AppState>| async {}))
        .with_state(state)
}

let app = routes(AppState {});

// We can now call `Router::into_make_service`
# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
# };
```

### axum::routing::Router::with_state (function) › A note about performance

If you need a `Router` that implements `Service` but you don't need any state (perhaps
you're making a library that uses axum internally) then it is recommended to call this
method before you start serving requests:

```rust
use axum::{Router, routing::get};

let app = Router::new()
    .route("/", get(|| async { /* ... */ }))
    // even though we don't need any state, call `with_state(())` anyway
    .with_state(());
# let _: Router = app;
```

This is not required but it gives axum a chance to update some internals in the router
which may impact performance and reduce allocations.

Note that [`Router::into_make_service`] and [`Router::into_make_service_with_connect_info`]
do this automatically.

[`Extension`]: crate::Extension

## axum::routing::RouterAsService (struct)

A [`Router`] converted into a borrowed [`Service`] with a fixed body type.

See [`Router::as_service`] for more details.

## axum::routing::RouterIntoService (struct)

A [`Router`] converted into an owned [`Service`] with a fixed body type.

See [`Router::into_service`] for more details.

## axum::routing::into_make_service::IntoMakeService (struct)

A [`MakeService`] that produces axum router services.

[`MakeService`]: tower::make::MakeService

## axum::routing::into_make_service::IntoMakeServiceFuture (struct)

Response future for [`IntoMakeService`].

## axum::routing::method_filter::MethodFilter (struct)

A filter that matches one or more HTTP methods.

## axum::routing::method_filter::MethodFilter::CONNECT (assoc_const)

Match `CONNECT` requests.

This is useful for implementing HTTP/2's [extended CONNECT method],
in which the `:protocol` pseudoheader is read
(using [`hyper::ext::Protocol`])
and the connection upgraded to a bidirectional byte stream
(using [`hyper::upgrade::on`]).

As seen in the [HTTP Upgrade Token Registry],
common uses include WebSockets and proxying UDP or IP –
though note that when using [`WebSocketUpgrade`]
it's more useful to use [`any`](crate::routing::any)
as HTTP/1.1 WebSockets need to support `GET`.

[extended CONNECT]: https://www.rfc-editor.org/rfc/rfc8441.html#section-4
[HTTP Upgrade Token Registry]: https://www.iana.org/assignments/http-upgrade-tokens/http-upgrade-tokens.xhtml
[`WebSocketUpgrade`]: crate::extract::WebSocketUpgrade

## axum::routing::method_filter::NoMatchingMethodFilter (struct)

Error type used when converting a [`Method`] to a [`MethodFilter`] fails.

## axum::routing::method_routing::MethodRouter (struct)

A [`Service`] that accepts requests based on a [`MethodFilter`] and
allows chaining additional handlers and services.

### axum::routing::method_routing::MethodRouter (struct) › When does `MethodRouter` implement [`Service`]?

Whether or not `MethodRouter` implements [`Service`] depends on the state type it requires.

```
use tower::Service;
use axum::{routing::get, extract::{State, Request}, body::Body};

// this `MethodRouter` doesn't require any state, i.e. the state is `()`,
let method_router = get(|| async {});
// and thus it implements `Service`
assert_service(method_router);

// this requires a `String` and doesn't implement `Service`
let method_router = get(|_: State<String>| async {});
// until you provide the `String` with `.with_state(...)`
let method_router_with_state = method_router.with_state(String::new());
// and then it implements `Service`
assert_service(method_router_with_state);

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

## axum::routing::method_routing::MethodRouter::fallback (function)

Add a fallback [`Handler`] to the router.

## axum::routing::method_routing::MethodRouter::get (function)

Chain an additional handler that will only accept `GET` requests.

### axum::routing::method_routing::MethodRouter::get (function) › Example

```rust
use axum::{routing::post, Router};

async fn handler() {}

async fn other_handler() {}

// Requests to `POST /` will go to `handler` and `GET /` will go to
// `other_handler`.
let app = Router::new().route("/", post(handler).get(other_handler));
# let _: Router = app;
```

Note that `get` routes will also be called for `HEAD` requests but will have
the response body removed. Make sure to add explicit `HEAD` routes
afterwards.

## axum::routing::method_routing::MethodRouter::get_service (function)

Chain an additional service that will only accept `GET` requests.

### axum::routing::method_routing::MethodRouter::get_service (function) › Example

```rust
use axum::{
    extract::Request,
    Router,
    routing::post_service,
    body::Body,
};
use http::Response;
use std::convert::Infallible;

let service = tower::service_fn(|request: Request| async {
    Ok::<_, Infallible>(Response::new(Body::empty()))
});

let other_service = tower::service_fn(|request: Request| async {
    Ok::<_, Infallible>(Response::new(Body::empty()))
});

// Requests to `POST /` will go to `service` and `GET /` will go to
// `other_service`.
let app = Router::new().route("/", post_service(service).get_service(other_service));
# let _: Router = app;
```

Note that `get` routes will also be called for `HEAD` requests but will have
the response body removed. Make sure to add explicit `HEAD` routes
afterwards.

## axum::routing::method_routing::MethodRouter::into_make_service_with_connect_info (function)

Convert the router into a [`MakeService`] which stores information
about the incoming connection.

See [`Router::into_make_service_with_connect_info`] for more details.

```rust
use axum::{
    handler::Handler,
    response::IntoResponse,
    extract::ConnectInfo,
    routing::get,
};
use std::net::SocketAddr;

async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
    format!("Hello {addr}")
}

let router = get(handler).post(handler);

# async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, router.into_make_service()).await.unwrap();
# };
```

[`MakeService`]: tower::make::MakeService
[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info

## axum::routing::method_routing::MethodRouter::layer (function)

Apply a [`tower::Layer`] to all routes in the router.

This can be used to add additional processing to a request for a group
of routes.

Note that the middleware is only applied to existing routes. So you have to
first add your routes (and / or fallback) and then call `layer` afterwards. Additional
routes added after `layer` is called will not have the middleware added.

Works similarly to [`Router::layer`](super::Router::layer). See that method for
more details.

### axum::routing::method_routing::MethodRouter::layer (function) › Example

```rust
use axum::{routing::get, Router};
use tower::limit::ConcurrencyLimitLayer;

async fn handler() {}

let app = Router::new().route(
    "/",
    // All requests to `GET /` will be sent through `ConcurrencyLimitLayer`
    get(handler).layer(ConcurrencyLimitLayer::new(64)),
);
# let _: Router = app;
```

## axum::routing::method_routing::MethodRouter::route_layer (function)

Apply a [`tower::Layer`] to the router that will only run if the request matches
a route.

Note that the middleware is only applied to existing routes. First add your routes and then call `route_layer`
afterwards. Additional routes added after `route_layer` is called will not have
the middleware added.

This works similarly to [`MethodRouter::layer`] except the middleware will only run if
the request matches a route. This is useful for middleware that return early
(such as authorization) which might otherwise convert a `405 Method Not Allowed` into a
`401 Unauthorized`.

### axum::routing::method_routing::MethodRouter::route_layer (function) › Example

```rust
use axum::{
    routing::get,
    Router,
};
use tower_http::validate_request::ValidateRequestHeaderLayer;

let app = Router::new().route(
    "/foo",
    get(|| async {})
        .route_layer(ValidateRequestHeaderLayer::bearer("password"))
);

// `GET /foo` with a valid token will receive `200 OK`
// `GET /foo` with a invalid token will receive `401 Unauthorized`
// `POST /FOO` with a invalid token will receive `405 Method Not Allowed`
# let _: Router = app;
```

## axum::routing::method_routing::any (function)

Route requests with the given handler regardless of the method.

### axum::routing::method_routing::any (function) › Example

```rust
use axum::{
    routing::any,
    Router,
};

async fn handler() {}

// All requests to `/` will go to `handler`.
let app = Router::new().route("/", any(handler));
# let _: Router = app;
```

Additional methods can still be chained:

```rust
use axum::{
    routing::any,
    Router,
};

async fn handler() {}

async fn other_handler() {}

// `POST /` goes to `other_handler`. All other requests go to `handler`
let app = Router::new().route("/", any(handler).post(other_handler));
# let _: Router = app;
```

## axum::routing::method_routing::any_service (function)

Route requests to the given service regardless of its method.

### axum::routing::method_routing::any_service (function) › Example

```rust
use axum::{
    extract::Request,
    Router,
    routing::any_service,
    body::Body,
};
use http::Response;
use std::convert::Infallible;

let service = tower::service_fn(|request: Request| async {
    Ok::<_, Infallible>(Response::new(Body::empty()))
});

// All requests to `/` will go to `service`.
let app = Router::new().route("/", any_service(service));
# let _: Router = app;
```

Additional methods can still be chained:

```rust
use axum::{
    extract::Request,
    Router,
    routing::any_service,
    body::Body,
};
use http::Response;
use std::convert::Infallible;

let service = tower::service_fn(|request: Request| async {
    # Ok::<_, Infallible>(Response::new(Body::empty()))
    // ...
});

let other_service = tower::service_fn(|request: Request| async {
    # Ok::<_, Infallible>(Response::new(Body::empty()))
    // ...
});

// `POST /` goes to `other_service`. All other requests go to `service`
let app = Router::new().route("/", any_service(service).post_service(other_service));
# let _: Router = app;
```

## axum::routing::method_routing::connect (function)

Route `CONNECT` requests to the given handler.

See [`MethodFilter::CONNECT`] for when you'd want to use this,
and [`get`] for an example.

## axum::routing::method_routing::connect_service (function)

Route `CONNECT` requests to the given service.

See [`MethodFilter::CONNECT`] for when you'd want to use this,
and [`get_service`] for an example.

## axum::routing::method_routing::delete (function)

Route `DELETE` requests to the given handler.

 See [`get`] for an example.

## axum::routing::method_routing::delete_service (function)

Route `DELETE` requests to the given service.

 See [`get_service`] for an example.

## axum::routing::method_routing::get (function)

Route `GET` requests to the given handler.

### axum::routing::method_routing::get (function) › Example

```rust
use axum::{
    routing::get,
    Router,
};

async fn handler() {}

// Requests to `GET /` will go to `handler`.
let app = Router::new().route("/", get(handler));
# let _: Router = app;
```

Note that `get` routes will also be called for `HEAD` requests but will have
the response body removed. Make sure to add explicit `HEAD` routes
afterwards.

## axum::routing::method_routing::get_service (function)

Route `GET` requests to the given service.

### axum::routing::method_routing::get_service (function) › Example

```rust
use axum::{
    extract::Request,
    Router,
    routing::get_service,
    body::Body,
};
use http::Response;
use std::convert::Infallible;

let service = tower::service_fn(|request: Request| async {
    Ok::<_, Infallible>(Response::new(Body::empty()))
});

// Requests to `GET /` will go to `service`.
let app = Router::new().route("/", get_service(service));
# let _: Router = app;
```

Note that `get` routes will also be called for `HEAD` requests but will have
the response body removed. Make sure to add explicit `HEAD` routes
afterwards.

## axum::routing::method_routing::head (function)

Route `HEAD` requests to the given handler.

 See [`get`] for an example.

## axum::routing::method_routing::head_service (function)

Route `HEAD` requests to the given service.

 See [`get_service`] for an example.

## axum::routing::method_routing::on (function)

Route requests with the given method to the handler.

### axum::routing::method_routing::on (function) › Example

```rust
use axum::{
    routing::on,
    Router,
    routing::MethodFilter,
};

async fn handler() {}

// Requests to `POST /` will go to `handler`.
let app = Router::new().route("/", on(MethodFilter::POST, handler));
# let _: Router = app;
```

## axum::routing::method_routing::on_service (function)

Route requests with the given method to the service.

### axum::routing::method_routing::on_service (function) › Example

```rust
use axum::{
    extract::Request,
    routing::on,
    Router,
    body::Body,
    routing::{MethodFilter, on_service},
};
use http::Response;
use std::convert::Infallible;

let service = tower::service_fn(|request: Request| async {
    Ok::<_, Infallible>(Response::new(Body::empty()))
});

// Requests to `POST /` will go to `service`.
let app = Router::new().route("/", on_service(MethodFilter::POST, service));
# let _: Router = app;
```

## axum::routing::method_routing::options (function)

Route `OPTIONS` requests to the given handler.

 See [`get`] for an example.

## axum::routing::method_routing::options_service (function)

Route `OPTIONS` requests to the given service.

 See [`get_service`] for an example.

## axum::routing::method_routing::patch (function)

Route `PATCH` requests to the given handler.

 See [`get`] for an example.

## axum::routing::method_routing::patch_service (function)

Route `PATCH` requests to the given service.

 See [`get_service`] for an example.

## axum::routing::method_routing::post (function)

Route `POST` requests to the given handler.

 See [`get`] for an example.

## axum::routing::method_routing::post_service (function)

Route `POST` requests to the given service.

 See [`get_service`] for an example.

## axum::routing::method_routing::put (function)

Route `PUT` requests to the given handler.

 See [`get`] for an example.

## axum::routing::method_routing::put_service (function)

Route `PUT` requests to the given service.

 See [`get_service`] for an example.

## axum::routing::method_routing::trace (function)

Route `TRACE` requests to the given handler.

 See [`get`] for an example.

## axum::routing::method_routing::trace_service (function)

Route `TRACE` requests to the given service.

 See [`get_service`] for an example.

## axum::routing::route::InfallibleRouteFuture (struct)

A [`RouteFuture`] that always yields a [`Response`].

## axum::routing::route::Route (struct)

How routes are stored inside a [`Router`](super::Router).

You normally shouldn't need to care about this type. It's used in
[`Router::layer`](super::Router::layer).

## axum::routing::route::RouteFuture (struct)

Response future for [`Route`].

## axum::run (function)

Execute the remaining middleware stack.

## axum::selected_protocol (function)

Return the selected WebSocket subprotocol, if one has been chosen.

If [`protocols()`][Self::protocols] selects a matching protocol, or
[`set_selected_protocol()`][Self::set_selected_protocol] has been called, the return
value will be `Some` containing the selected protocol. Otherwise, it will be `None`.

## axum::send (function)

Send a message.

## axum::serve::IncomingStream (struct)

An incoming stream.

Used with [`serve`] and [`IntoMakeServiceWithConnectInfo`].

[`IntoMakeServiceWithConnectInfo`]: crate::extract::connect_info::IntoMakeServiceWithConnectInfo

## axum::serve::Serve (struct)

Future returned by [`serve`].

## axum::serve::WithGracefulShutdown (struct)

Serve future with graceful shutdown enabled.

## axum::serve::listener::Listener (trait)

Types that can listen for connections.

## axum::serve::listener::ListenerExt (trait)

Extensions to [`Listener`].

## axum::serve::listener::ListenerExt::tap_io (function)

Run a mutable closure on every accepted `Io`.

### axum::serve::listener::ListenerExt::tap_io (function) › Example

```
use axum::{Router, routing::get, serve::ListenerExt};
use tracing::trace;

# async {
let router = Router::new().route("/", get(|| async { "Hello, World!" }));

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
    .await
    .unwrap()
    .tap_io(|tcp_stream| {
        if let Err(err) = tcp_stream.set_nodelay(true) {
            trace!("failed to set TCP_NODELAY on incoming connection: {err:#}");
        }
    });
axum::serve(listener, router).await.unwrap();
# };
```

## axum::serve::listener::TapIo (struct)

Return type of [`ListenerExt::tap_io`].

See that method for details.

## axum::serve::serve (function)

Serve the service with the supplied listener.

This method of running a service is intentionally simple and doesn't support any configuration.
Use hyper or hyper-util if you need configuration.

It supports both HTTP/1 as well as HTTP/2.

### axum::serve::serve (function) › Examples

Serving a [`Router`]:

```
use axum::{Router, routing::get};

# async {
let router = Router::new().route("/", get(|| async { "Hello, World!" }));

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, router).await.unwrap();
# };
```

See also [`Router::into_make_service_with_connect_info`].

Serving a [`MethodRouter`]:

```
use axum::routing::get;

# async {
let router = get(|| async { "Hello, World!" });

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, router).await.unwrap();
# };
```

See also [`MethodRouter::into_make_service_with_connect_info`].

Serving a [`Handler`]:

```
use axum::handler::HandlerWithoutStateExt;

# async {
async fn handler() -> &'static str {
    "Hello, World!"
}

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, handler.into_make_service()).await.unwrap();
# };
```

See also [`HandlerWithoutStateExt::into_make_service_with_connect_info`] and
[`HandlerService::into_make_service_with_connect_info`].

### axum::serve::serve (function) › Return Value

Although this future resolves to `io::Result<()>`, it will never actually complete or return an
error. Errors on the TCP socket will be handled by sleeping for a short while (currently, one
second).

[`Router`]: crate::Router
[`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info
[`MethodRouter`]: crate::routing::MethodRouter
[`MethodRouter::into_make_service_with_connect_info`]: crate::routing::MethodRouter::into_make_service_with_connect_info
[`Handler`]: crate::handler::Handler
[`HandlerWithoutStateExt::into_make_service_with_connect_info`]: crate::handler::HandlerWithoutStateExt::into_make_service_with_connect_info
[`HandlerService::into_make_service_with_connect_info`]: crate::handler::HandlerService::into_make_service_with_connect_info

## axum::service_ext::ServiceExt (trait)

Extension trait that adds additional methods to any [`Service`].

## axum::state (function)

Get a reference to the state.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status (function)

Get the status code used for this rejection.

## axum::status_code (function)

Returns the HTTP status code of the `Redirect`.

## axum::text (function)

Create a new text WebSocket message from a stringable.

## axum::text (function)

Customize the text of the keep-alive message.

Default is an empty comment.

### axum::text (function) › Panics

Panics if `text` contains any newline or carriage returns, as they are not allowed in SSE
comments.

## axum::text (function)

Get the full field data as text.

## axum::to_text (function)

Attempt to get a &str from the WebSocket message,
this will try to convert binary data to utf8.

## axum::trace (function)

Chain an additional handler that will only accept `TRACE` requests.

 See [`MethodRouter::get`] for an example.

## axum::trace_service (function)

Chain an additional service that will only accept `TRACE` requests.

 See [`MethodRouter::get_service`] for an example.

## axum::try_from_uri (function)

Attempts to construct a [`Query`] from a reference to a [`Uri`].

### axum::try_from_uri (function) › Example
```
use axum::extract::Query;
use http::Uri;
use serde::Deserialize;

#[derive(Deserialize)]
struct ExampleParams {
    foo: String,
    bar: u32,
}

let uri: Uri = "http://example.com/path?foo=hello&bar=42".parse().unwrap();
let result: Query<ExampleParams> = Query::try_from_uri(&uri).unwrap();
assert_eq!(result.foo, String::from("hello"));
assert_eq!(result.bar, 42);
```

## axum::value (struct_field)

The value from the URI.

## axum::value (struct_field)

The value from the URI.

## axum::value (struct_field)

The value from the URI.

## axum::value (struct_field)

The value that failed to deserialize.

## axum::with_graceful_shutdown (function)

Prepares a server to handle graceful shutdown when the provided future completes.

### axum::with_graceful_shutdown (function) › Example

```
use axum::{Router, routing::get};

# async {
let router = Router::new().route("/", get(|| async { "Hello, World!" }));

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, router)
    .with_graceful_shutdown(shutdown_signal())
    .await
    .unwrap();
# };

async fn shutdown_signal() {
    // ...
}
```

### axum::with_graceful_shutdown (function) › Return Value

Similarly to [`serve`], although this future resolves to `io::Result<()>`, it will never
error. It returns `Ok(())` only after the `signal` future completes.

## axum::with_state (function)

Provide the state for the router.

## axum::without_v07_checks (function)

Turn off checks for compatibility with route matching syntax from 0.7.

This allows usage of paths starting with a colon `:` or an asterisk `*` which are otherwise prohibited.

### axum::without_v07_checks (function) › Example

```rust
use axum::{
    routing::get,
    Router,
};

let app = Router::<()>::new()
    .without_v07_checks()
    .route("/:colon", get(|| async {}))
    .route("/*asterisk", get(|| async {}));

// Our app now accepts
// - GET /:colon
// - GET /*asterisk
# let _: Router = app;
```

Adding such routes without calling this method first will panic.

```rust,should_panic
use axum::{
    routing::get,
    Router,
};

// This panics...
let app = Router::<()>::new()
    .route("/:colon", get(|| async {}));
```

### axum::without_v07_checks (function) › Merging

When two routers are merged, v0.7 checks are disabled for route registrations on the resulting router if both of the two routers had them also disabled.

### axum::without_v07_checks (function) › Nesting

Each router needs to have the checks explicitly disabled. Nesting a router with the checks either enabled or disabled has no effect on the outer router.

