pub trait IntoResponse {
    fn into_response(self) -> Response;
}
Expand description

Trait for generating responses.

Types that implement IntoResponse can be returned from handlers.

Implementing IntoResponse

You generally shouldn’t have to implement IntoResponse manually, as axum provides implementations for many common types.

However it might be necessary if you have a custom error type that you want to return from handlers:

use axum::{
    Router,
    body::{self, Bytes},
    routing::get,
    http::StatusCode,
    response::{IntoResponse, Response},
};

enum MyError {
    SomethingWentWrong,
    SomethingElseWentWrong,
}

impl IntoResponse for MyError {
    fn into_response(self) -> Response {
        let body = match self {
            MyError::SomethingWentWrong => {
                body::boxed(body::Full::from("something went wrong"))
            },
            MyError::SomethingElseWentWrong => {
                body::boxed(body::Full::from("something else went wrong"))
            },
        };

        Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .body(body)
            .unwrap()
    }
}

// `Result<impl IntoResponse, MyError>` can now be returned from handlers
let app = Router::new().route("/", get(handler));

async fn handler() -> Result<(), MyError> {
    Err(MyError::SomethingWentWrong)
}

Or if you have a custom body type you’ll also need to implement IntoResponse for it:

use axum::{
    body,
    routing::get,
    response::{IntoResponse, Response},
    Router,
};
use http_body::Body;
use http::HeaderMap;
use bytes::Bytes;
use std::{
    convert::Infallible,
    task::{Poll, Context},
    pin::Pin,
};

struct MyBody;

// First implement `Body` for `MyBody`. This could for example use
// some custom streaming protocol.
impl Body for MyBody {
    type Data = Bytes;
    type Error = Infallible;

    fn poll_data(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>
    ) -> Poll<Option<Result<Self::Data, Self::Error>>> {
        // ...
    }

    fn poll_trailers(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>
    ) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
        // ...
    }
}

// Now we can implement `IntoResponse` directly for `MyBody`
impl IntoResponse for MyBody {
    fn into_response(self) -> Response {
        Response::new(body::boxed(self))
    }
}

// We don't need to implement `IntoResponse for Response<MyBody>` as that is
// covered by a blanket implementation in axum.

// `MyBody` can now be returned from handlers.
let app = Router::new().route("/", get(|| async { MyBody }));

Required methods

Create a response.

Implementations on Foreign Types

Implementors