HTTP Response Structure

Learn how an HTTP response is built from a status line, headers, and body, and see how Axum handlers generate these responses with practical code examples.

Every conversation over the web follows the same rhythm: a client sends a request, and a server sends back a response. A request carries the client's question. This page flips the direction and looks at the answer. An HTTP response is not just the HTML page or the JSON data you see in a browser. Underneath that content, the server always sends a structured message made of three distinct pieces: a status line, a set of headers, and an optional body.

Understanding these three pieces matters because every web framework, including Axum, ultimately builds its responses from them. When you write a handler in Axum and return a string, Axum quietly fills in the status line and headers for you. But the moment you need to return a 404 Not Found, set a custom header, or stream a large file, you must know what those hidden layers are.

What an HTTP response actually looks like

Before seeing any code, let's look at a real HTTP response exactly as it travels across the network. When a browser asks for http://example.com/, the server might answer with raw text like this:

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 176
Date: Wed, 21 Oct 2026 07:28:00 GMT
Server: ECS (dcb/7F84)
<!DOCTYPE html>
<html>
<head>
  <title>Example Domain</title>
</head>
<body>
  <h1>Example Domain</h1>
  <p>This domain is for use in illustrative examples.</p>
</body>
</html>

The first line is the status line. It tells the client the HTTP version, a three-digit status code, and a short reason phrase. After that come the headers, each on its own line as a Name: Value pair. A blank line separates the headers from the body. The body is the actual content - in this case an HTML page.

That blank line is not decorative. It is the separator the client uses to know where the headers end and the body begins. Without it, the client could not tell the difference between a header and a piece of the body.

The status line and status code

The status line contains the most important piece of information for the client: whether the request worked or failed. The status code is a three-digit number that categorizes the result. The reason phrase (OK, Not Found, Internal Server Error) is a human-readable label for that number, but the number itself is what software relies on.

Here are a few status codes you will see constantly:

CodeReason PhraseWhat it means
200OKThe request succeeded and the body contains the requested data.
201CreatedThe request created a new resource. Often used after POST.
204No ContentThe request succeeded but there is no body to send back.
400Bad RequestThe client sent something the server could not understand.
404Not FoundThe requested path or resource does not exist.
500Internal Server ErrorSomething went wrong on the server while processing the request.

This page does not dive into every range of status codes - the focus here is the shape of a response, not the full catalogue of codes. For now, the key idea is that the status code is the first thing a client looks at when it receives a response. It determines whether the client should try to parse the body, show an error page, redirect somewhere else, or take any other action.

The status code is separate from the body:

A response can have a 200 OK status and still contain an error message in the body. That would be a poorly designed API, but it is possible. Likewise, a 404 Not Found response can include a helpful HTML page explaining what was not found. The status code is the machine-readable truth; the body is the human-readable explanation.

When you build a response in Axum, you often set the status code explicitly. The status code is what matters: the reason phrase is only a human-readable label that clients ignore, and HTTP/2 has no reason phrase at all, so you never need to write OK or Not Found yourself.

Response headers

Headers are metadata about the response. They do not contain the actual content the user asked for; they describe how that content should be interpreted, cached, or handled. Each header is a key-value pair. The key is case-insensitive (Content-Type and content-type mean the same thing), but the convention is to write them in capitalized hyphenated form.

Some headers you will see on almost every response:

  • Content-Type - tells the client what format the body is in, like text/html, application/json, or image/png.
  • Content-Length - the size of the body in bytes. This lets the client know when it has received the entire body.
  • Server - identifies the software that generated the response, such as nginx or axum.
  • Date - the date and time the response was generated, in GMT.

Headers are not just for the browser. Caches, proxies, and search engine crawlers all read headers to decide what to do with a response. For example, a Cache-Control header tells a browser how long it may keep a copy of the page before asking the server again.

In Axum, you can set headers in a few different ways, which we will see shortly. The important mental model is that headers are a separate layer from the body. You can change a header without touching the body at all.

The response body

The body is the actual payload - the HTML page, the JSON object, the image bytes, the downloaded file. It comes after the blank line that follows the headers. The body is optional. A response with status 204 No Content or 304 Not Modified typically has no body at all, because there is nothing meaningful to send.

The body can be any sequence of bytes. HTTP does not care whether those bytes represent text, an image, a video, or a compressed archive. The Content-Type header is what tells the client how to interpret those bytes. If you send HTML but set Content-Type: text/plain, the browser will display the raw HTML tags as text instead of rendering them as a page.

A body can also be streamed. Instead of the server generating the entire body in memory before sending it, it can send chunks as they become ready. This is useful for large files or live data. Axum supports streaming through its Body type, which is built on top of the HTTP engine Hyper. For beginners, the important part is that the body is just the raw content after the headers.

How Axum represents responses

In Axum, a handler function returns a value that can be converted into an HTTP response. Axum defines a trait called IntoResponse for this. If a type implements IntoResponse, Axum can call a method on it to produce the status line, headers, and body. This is why you can return a simple string from a handler and Axum automatically turns it into a 200 OK response with Content-Type: text/plain and the string as the body.

Here is the smallest possible Axum server that returns a response:

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The closure returns &'static str. Axum sees that, converts it into a response with status 200, header Content-Type: text/plain; charset=utf-8, and the bytes of the string as the body. That is a full HTTP response built from three lines of handler code.

Basic response types you can return

Axum implements IntoResponse for many common Rust types, so you rarely need to build a response from scratch. Each one produces a different combination of status, headers, and body.

Returning a plain text string

use axum::{routing::get, Router};
async fn plain_text() -> &'static str {
    "This is plain text"
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(plain_text));
    // server setup omitted for brevity
}

The response has status 200 OK, header Content-Type: text/plain; charset=utf-8, and the body is the string. Any String or &str can be returned this way.

Returning a status code only

use axum::{http::StatusCode, routing::get, Router};
async fn no_content() -> StatusCode {
    StatusCode::NO_CONTENT
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/ping", get(no_content));
    // server setup omitted
}

Here the handler returns a StatusCode. Axum produces a response with that status and no body. The headers are minimal. This is useful for endpoints that just need to acknowledge an action without sending any data back.

Returning a tuple with status and body

Often you want both a non-200 status and a body. Axum lets you return a tuple where the first element is a StatusCode and the second element is something that implements IntoResponse:

use axum::{http::StatusCode, routing::get, Router};
async fn not_found() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "The page you requested does not exist")
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/missing", get(not_found));
    // server setup omitted
}

The tuple produces a 404 Not Found response with the string as the body. Axum still automatically sets Content-Type: text/plain because the body is a string. You can extend the tuple further to include headers, which we will see soon.

Returning structured data like JSON and HTML

Plain text is fine for simple messages, but real APIs usually send JSON, and web pages send HTML. Axum provides wrapper types that set the correct Content-Type header automatically.

JSON responses

use axum::{routing::get, Json, Router};
use serde_json::{json, Value};
async fn json_response() -> Json<Value> {
    Json(json!({
        "message": "Hello from Axum",
        "success": true
    }))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/api/greet", get(json_response));
    // server setup omitted
}

The Json wrapper tells Axum to serialize the value into JSON and set Content-Type: application/json. The body is the JSON text. This is the most common response type in REST APIs.

HTML responses

use axum::{response::Html, routing::get, Router};
async fn html_page() -> Html<&'static str> {
    Html("<h1>Welcome</h1><p>This is an HTML page.</p>")
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(html_page));
    // server setup omitted
}

The Html wrapper sets Content-Type: text/html; charset=utf-8. The browser will render the tags as a web page.

You are on the right track:

If you have written a handler that returns one of these types and your server starts successfully, then Axum is generating a valid HTTP response for every request. The client will see a status line, headers, and body that make sense together.

Setting custom headers

Sometimes the automatic headers are not enough. You might need to add a cache-control header, a custom tracking header, or set CORS headers. Axum gives you several ways to do this. The most straightforward is to include headers as part of a tuple.

The tuple form for a response with status, headers, and body is (StatusCode, [(HeaderName, HeaderValue); N], Body). The second element is an array of header pairs. Each pair sets one header on the response.

use axum::{
    http::{header, StatusCode},
    routing::get,
    Router,
};
async fn with_custom_header() -> (
    StatusCode,
    [(header::HeaderName, &'static str); 1],
    &'static str,
) {
    (
        StatusCode::OK,
        [(header::CACHE_CONTROL, "no-store")],
        "This response must not be cached",
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/private", get(with_custom_header));
    // server setup omitted
}

The array [(header::CACHE_CONTROL, "no-store")] adds a Cache-Control: no-store header to the response. You can include multiple pairs by increasing the array length. This approach works when you need to set a few headers at return time.

If you need more control - for example, setting a header conditionally based on the request - you can build a Response object manually. We will explore that in a moment.

Building a response with the Response builder

For complete control over the status line, headers, and body, Axum exposes the Response type from the http crate. You can create a builder, set each part, and then convert it into an IntoResponse.

use axum::{
    body::Body,
    http::{header, Response, StatusCode},
    routing::get,
    Router,
};
async fn built_response() -> Response<Body> {
    Response::builder()
        .status(StatusCode::CREATED)
        .header(header::CONTENT_TYPE, "text/plain")
        .header("Acme-Custom-Header", "hello")
        .body(Body::from("Resource created successfully"))
        .unwrap()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/create", get(built_response));
    // server setup omitted
}

Here the builder starts empty, then we set the status to 201 Created, add two headers, and finally attach a body. The unwrap() is safe in practice because the builder only fails if you set an invalid header value or forget the body. This approach is more verbose but gives you full control.

A common beginner mistake:

When using Response::builder(), do not forget the .body() call. If you return the builder itself without building a full Response, the code will not compile. The builder is not a response; it is a recipe for creating one. Always finish with .body(...) and handle the Result appropriately.

Returning nothing at all

Some endpoints need to respond with a status but no body. The simplest way is to return a StatusCode directly, as shown earlier. That works well for 204 No Content, 304 Not Modified, or 202 Accepted when you don't have anything to send back.

You can also return an empty tuple () from a handler. Axum interprets that as 200 OK with no body.

use axum::{routing::post, Router};
async fn do_nothing() {
    // handler does some work but returns nothing
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/fire-and-forget", post(do_nothing));
    // server setup omitted
}

A handler returning () is useful when the client does not need any data back, just a confirmation that the request was processed.

Comparing multiple ways to create the same response

There is rarely one "correct" way to return a response in Axum. Different situations call for different levels of control. The following three approaches all produce a 200 OK response with the body "data" and Content-Type: text/plain:

Approach 1: Return a string

async fn approach1() -> &'static str {
    "data"
}

This is the shortest and most idiomatic when you want a simple text response.

Approach 2: Return a tuple with status and body

async fn approach2() -> (axum::http::StatusCode, &'static str) {
    (axum::http::StatusCode::OK, "data")
}

This is useful when you need to specify the status code but keep the body simple.

Approach 3: Build a Response manually

async fn approach3() -> axum::response::Response {
    axum::response::Response::builder()
        .status(axum::http::StatusCode::OK)
        .header("Content-Type", "text/plain")
        .body(axum::body::Body::from("data"))
        .unwrap()
}

This is necessary when you need to set many headers, use a non-standard status, or dynamically decide what to include. It is the most verbose, so use it only when the simpler forms are not flexible enough.

Choosing among these is a judgment call. For a REST API returning JSON, the Json wrapper is almost always the right choice. For a custom error page with a specific status and headers, the builder gives you precise control.

How the client sees the response

To make this concrete, imagine a handler that returns a JSON response with a custom header. The client sends a request and receives the raw HTTP response. Here is what that looks like on the wire:

HTTP/1.1 200 OK
content-type: application/json
x-request-id: 12345
content-length: 26
date: Wed, 21 Oct 2026 07:30:00 GMT
{"message":"Hello, Axum!"}

The status line is HTTP/1.1 200 OK. The headers include the auto-generated content-type, a custom x-request-id, and content-length. Then the blank line, then the JSON body. Any HTTP client - a browser, curl, or another server - parses this structure exactly the same way.

Common mistakes and how to fix them

Forgetting to set Content-Type

If you return a plain string from a handler, Axum sets Content-Type: text/plain. But if you build a response manually and forget to set Content-Type, the client will not know how to interpret the body. Many clients will guess, but that can lead to incorrect rendering. Always set Content-Type when the body is not plain text.

Mixing up status codes

A 200 OK response with an error message in the body is confusing for API consumers. Use 4xx codes for client errors and 5xx codes for server errors. Return 404 when something is not found, 400 when the request is malformed, and 500 when an unexpected error occurs.

Returning the wrong type from a handler

Axum requires that the return type of a handler implement IntoResponse. If you try to return something that does not implement it, the compiler will complain. The error messages in Axum 0.8 are designed to point you toward what is missing, but the fix is usually to wrap the value in a type like Json or Html, or return a tuple.

A silent failure you must avoid:

When you build a Response with Response::builder(), calling .unwrap() on the result can panic at runtime if you accidentally set an invalid header value. In a running server, that panic aborts the task handling that one request, so the client gets no response at all - the server itself keeps running and other requests are unaffected. For production code, handle the Result properly or ensure your header values are always valid ASCII strings. The examples in this page use .unwrap() only for brevity.

A step-by-step guide to deciding what to return

When you sit down to write an Axum handler, the response you return should follow a consistent thought process. Here is a sequence you can use to make the decision.

1

Step 1: Decide what the client should receive

Ask what data the client needs. If the client requested a list of users, the response should be JSON. If the client requested a web page, the response should be HTML. If the client just created a resource, the response might be a 201 Created with a link to the new resource.

2

Step 2: Choose the status code

Match the status code to the outcome. A successful read or creation maps to 200 or 201. A missing resource maps to 404. A validation error maps to 400. An unexpected failure maps to 500. The status code is the first thing the client checks, so it must accurately reflect what happened.

3

Step 3: Determine the headers

Most headers are set automatically by Axum, especially Content-Type and Content-Length. You only need to add custom headers when you have a specific requirement, like cache control, authentication challenges, or request tracking. If you need a custom header, use a tuple or the Response builder.

4

Step 4: Pick the return type that gives you the right amount of control

If a simple string or Json wrapper covers all three previous decisions, use that. If you need a non-standard status or custom headers, use a tuple. If you need to set many headers dynamically or build a streaming body, use Response::builder().

This sequence is not a rigid rule. Sometimes the simplest path is to return a StatusCode and nothing else. But walking through these four questions helps you avoid returning a 200 when you meant 404, or forgetting that the body should be JSON.

Summary

An HTTP response is a three-part structure: a status line with a numeric code, a set of headers describing the content, and an optional body carrying the actual data. Clients rely on the status code to decide what to do, on the headers to interpret the body, and on the body for the actual content.

Axum hides most of this structure behind the IntoResponse trait. Returning a string, a StatusCode, a tuple, or a Json wrapper all produce a valid HTTP response with appropriate defaults. When those defaults are not enough, the Response builder gives you direct access to every part.

The single most important insight to carry forward is that the status code and the body are two separate pieces of information. A successful response can have an empty body, and an error response can have a helpful HTML body. When you build an API, keep those two layers distinct in your mind, and your handlers will produce responses that are easy for clients to understand and for you to debug.