Chuyển đến nội dung

Bài 15 · Extractors and Responses

Responses and IntoResponse in Axum

Build Axum responses with the IntoResponse trait: strings, status tuples, headers, Json, Html, Redirect, Result, Response::builder, streaming and server-sent events.

Extractors take a request apart; responses put one together. In Axum a handler can return a surprising variety of types (a string, a tuple, a Json, a Result) because every one of them implements a single trait: IntoResponse. Axum calls into_response() on the return value and gets the real HTTP response.

Knowing which types implement the trait, and how tuples compose, lets you write handlers that read like a description of the answer: (StatusCode::CREATED, Json(user)).

The trait

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

Response is http::Response<axum::body::Body>. Anything you can turn into one is a valid return type. Axum ships implementations for:

Return type Status Content-Type
&'static str, String 200 text/plain; charset=utf-8
Vec<u8>, Bytes, &'static [u8] 200 application/octet-stream
() 200 none, empty body
StatusCode that status none, empty body
Json<T> 200 application/json
Html<T> 200 text/html; charset=utf-8
Redirect 303, 307 or 308 location header
Response<B> whatever you built whatever you set
Result<T, E> where both implement IntoResponse from Ok or Err from the chosen side

Tuples: status, headers and body together

A tuple implements IntoResponse when its last element does, and the elements before it are "response parts" that adjust the response:

Rust
use axum::{http::{header, StatusCode}, response::IntoResponse, Json};

async fn created() -> impl IntoResponse {
    (
        StatusCode::CREATED,                                   // status
        [(header::LOCATION, "/users/42")],                     // headers
        Json(serde_json::json!({ "id": 42 })),                 // body
    )
}

The allowed prefixes, in order: an optional StatusCode (or a full Parts value), then any number of header sets ([(name, value); N], HeaderMap, AppendHeaders), then the body. If you omit the status, it is 200. Anything that implements IntoResponseParts, such as CookieJar from the previous lesson, can appear among the parts.

A common bug is returning a bare string from a handler that should answer an error: it yields 200 OK. Add the status:

Rust
async fn teapot() -> (StatusCode, &'static str) {
    (StatusCode::IM_A_TEAPOT, "short and stout")
}

impl IntoResponse and Result

If a handler can return different types on different paths, return Response (via .into_response()) or a common enum, or use Result:

Rust
async fn get_user(Path(id): Path<u64>) -> Result<Json<User>, StatusCode> {
    match find(id) {
        Some(user) => Ok(Json(user)),
        None => Err(StatusCode::NOT_FOUND),
    }
}

impl IntoResponse hides the concrete type but still requires that all branches return the same type. When they do not, call .into_response() on each branch:

Rust
async fn mixed(flag: bool) -> impl IntoResponse {
    if flag {
        "text".into_response()
    } else {
        (StatusCode::NO_CONTENT).into_response()
    }
}

In error handling you will replace StatusCode as the error with your own type that implements IntoResponse.

HTML, redirects and the status you choose

Rust
use axum::response::{Html, Redirect};

async fn home() -> Html<&'static str> {
    Html("<h1>Welcome</h1>")
}

async fn old_page() -> Redirect {
    Redirect::permanent("/new-page")   // 308
}

async fn after_form() -> Redirect {
    Redirect::to("/thanks")            // 303 See Other
}
Constructor Status Meaning
Redirect::to(uri) 303 after a POST, show the result with a GET
Redirect::temporary(uri) 307 repeat the same method and body elsewhere
Redirect::permanent(uri) 308 the resource moved for good, keep the method

For template engines (Askama, Maud, minijinja) return the rendered string inside Html. Askama templates can implement IntoResponse directly.

Building a response by hand

Response::builder() is the long form, for cases where you compute everything:

Rust
use axum::{body::Body, http::{header, Response, StatusCode}};

async fn raw() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
        .header("x-served-by", "axum-demo")
        .body(Body::from("built by hand"))
        .unwrap()
}

The builder returns a Result because a header name or value can be invalid. With constants and literals unwrap() is acceptable; with user data, handle the error.

Streaming and server-sent events

A Body can be built from a stream, so a big file or a slow producer is sent in chunks rather than buffered:

Rust
use axum::body::Body;
use tokio_util::io::ReaderStream;

async fn big_file() -> Result<impl IntoResponse, StatusCode> {
    let file = tokio::fs::File::open("report.csv").await.map_err(|_| StatusCode::NOT_FOUND)?;
    let body = Body::from_stream(ReaderStream::new(file));
    Ok(([(header::CONTENT_TYPE, "text/csv")], body))
}

Server-sent events (a one-way push channel that browsers consume with EventSource) use axum::response::sse::{Sse, Event} with a stream of Result<Event, Infallible>:

Rust
use axum::response::sse::{Event, KeepAlive, Sse};
use std::{convert::Infallible, time::Duration};
use tokio_stream::{wrappers::IntervalStream, StreamExt};

async fn ticks() -> Sse<impl tokio_stream::Stream<Item = Result<Event, Infallible>>> {
    let stream = IntervalStream::new(tokio::time::interval(Duration::from_secs(1)))
        .map(|_| Ok(Event::default().data("tick")));
    Sse::new(stream).keep_alive(KeepAlive::default())
}

SSE is a good fit for progress bars and live feeds; use WebSockets (axum::extract::ws) when the client must send messages back.

Stand-in: an IntoResponse trait with tuples

This model implements the same layering with std-only Rust: a Response struct, a trait with into_response, and implementations for strings, a status code, a header array, a JSON-like wrapper and tuples. Run it, then add your own combination, for example (Status(404), "missing").

Rust Stand-in: IntoResponse for strings, tuples and Result

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

Program input · what you'd type while the program runs

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

The 404 comes from the Err side of a Result, and its body still has a plain-text content type from the &str implementation. That is the composition Axum performs for you.

Stand-in: choosing a representation

A handler can serve the same data as JSON or HTML depending on the Accept header. Here is the decision logic in a small model, with a simple Accept parser that respects q weights.

Rust Stand-in: content negotiation with Accept

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

Program input · what you'd type while the program runs

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

Practical advice

  • Prefer explicit tuples over bare strings whenever the status is not 200.
  • Keep handlers returning small, concrete types; use impl IntoResponse only if the branch types match.
  • Set cache-control deliberately: no-store for private data, a max-age for public assets.
  • Stream large bodies instead of building them in memory.
  • Add #[axum::debug_handler] when a return type does not compile; it points to the exact problem.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What status does an Axum handler returning just the string "not found" send?

    A string implements IntoResponse with status 200 and a text/plain content type. Use a tuple to set another status.
  2. 2. In the tuple (StatusCode::CREATED, [(header::LOCATION, "/users/1")], Json(user)), which element must implement IntoResponse itself?

    The last element is the body. The earlier ones are parts that adjust the status and headers.
  3. 3. Which redirect should follow a successful form POST so the browser shows the result with a GET?

    303 See Other tells the client to fetch the new location with GET, which avoids re-submitting the form.
  4. 4. Why use Body::from_stream for a big file?

    Streaming keeps memory use small, whatever the file size.

Summary

  • Handlers return anything implementing IntoResponse: strings, (), StatusCode, Json, Html, Redirect, Response, and Result of two such types.
  • Tuples compose (status, headers..., body); the last element is the body.
  • Always set the status when it is not 200; strings alone mean 200 OK.
  • Response::builder(), streamed bodies and Sse cover the unusual cases.

Next: Shared State with State

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.