Returning Status, Headers, and Body Together
Learn how to build a complete HTTP response in Axum using the (StatusCode, HeaderMap, Body) tuple, including status codes, custom headers, body content, common mistakes, and practical examples.
When you build a web server, every handler ends by sending a response back to the client. That response always has three parts: a status code (like 200 for success or 404 for not found), a set of headers (extra information like content type), and a body (the actual data). Axum gives you many ways to return these parts, but the most explicit and flexible way is to put all three together in a tuple: (StatusCode, HeaderMap, Body).
This page focuses on that exact tuple. Here we combine them into one complete response that you fully control: the status code, the headers, and the body, all decided in one place. You will learn when to use this combination, how to build each piece, and how to avoid the mistakes beginners often make.
Why This Tuple Exists
Sometimes a handler needs to send a response where the status code, headers, and body all depend on the situation. For example, you might want to return a 201 Created status with a custom Location header and a JSON body after creating a new resource. Or you might need to return a 404 Not Found status with an X-Reason header and a short text body explaining what went wrong.
Axum allows you to return many simpler types like &'static str or String, which automatically produce a 200 OK response with default headers and a text body. However, those shortcuts don't let you set a custom status or add extra headers. The tuple (StatusCode, HeaderMap, Body) removes those limits. It gives you direct control over every part of the HTTP response without forcing you to use a builder or manual Response object.
The tuple works because Axum implements IntoResponse for tuples where the last element implements IntoResponse and the elements before it implement IntoResponseParts. HeaderMap implements IntoResponseParts, and Body implements IntoResponse. StatusCode is a special case: it does not implement IntoResponseParts, so Axum provides dedicated tuple forms with the status code first. When you return (StatusCode, HeaderMap, Body), Axum builds the response from the Body, merges the headers from the HeaderMap, and then applies the StatusCode as the response status. The result is a single complete HTTP response.
A First Complete Example
Let's start with a tiny Axum application that uses (StatusCode, HeaderMap, Body) to send a custom response. This example creates a handler that always returns a 200 OK status, a Content-Type header of text/plain, and the body "Hello from Axum".
// src/main.rs
use axum::{
http::{header, HeaderMap, StatusCode},
body::Body,
routing::get,
Router,
};
async fn custom_response() -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
(
StatusCode::OK,
headers,
Body::from("Hello from Axum"),
)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(custom_response));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
What is happening here? The function custom_response returns exactly the type (StatusCode, HeaderMap, Body). Inside it, we first create an empty HeaderMap and insert one header: Content-Type with the value "text/plain". The .parse().unwrap() converts the string into a HeaderValue, which is what HeaderMap expects. Then we build the tuple: StatusCode::OK for a successful status, the headers map we just made, and a Body created from a string using Body::from. Axum will send all three pieces as one response.
If you run this server and open http://127.0.0.1:3000 in a browser or with curl, you will see the text Hello from Axum. The response headers will include Content-Type: text/plain automatically because we set it. The status code will be 200. This is the simplest possible complete response with full control.
Working Setup:
If your browser displays "Hello from Axum" and your developer tools show a 200 status with a Content-Type of text/plain, you have correctly returned a (StatusCode, HeaderMap, Body) response.
Breaking Down the Three Pieces
Before going further, let's look at each part of the tuple individually so you understand exactly what you are building.
StatusCode
StatusCode is a struct from the axum::http module that wraps a 16-bit unsigned integer representing every HTTP status code defined in the standard. You use associated constants like StatusCode::OK, StatusCode::NOT_FOUND, StatusCode::CREATED, or StatusCode::INTERNAL_SERVER_ERROR. You can also use StatusCode::from_u16(201) to create a status from a number, but using the named constants is clearer. The status code tells the client whether the request succeeded, failed, or needs further action.
HeaderMap
HeaderMap is a collection of HTTP headers. Each header is a key-value pair. Keys are HeaderName values (like header::CONTENT_TYPE), and values are HeaderValue values. You create a HeaderMap with HeaderMap::new(), then insert entries using insert. You must make the map mutable before inserting. A HeaderMap can hold many headers; each one will be included in the response. Note that the order you insert headers is not guaranteed to be the order the client sees them, so never rely on header order.
Body
Body is a type that represents the bytes of the response body. It can be created from many sources: String, &'static str, Vec<u8>, Bytes, or even an empty body using Body::empty(). For small static content it just wraps the bytes you give it. When the tuple is converted into a response, Axum takes this Body and uses it as the response payload.
The power of the tuple is that you decide all three at once.
Adding Multiple Headers
A single Content-Type header is useful, but real responses often need more than one header. You can insert as many headers as you like into the same HeaderMap.
use axum::{
http::{header, HeaderMap, StatusCode},
body::Body,
routing::get,
Router,
};
async fn detailed_response() -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
headers.insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
headers.insert("X-Custom-Header", "my-value".parse().unwrap());
(
StatusCode::OK,
headers,
Body::from(r#"{"message":"hello"}"#),
)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(detailed_response));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Here we add three headers: Content-Type set to JSON, Cache-Control set to no-store, and a custom header named X-Custom-Header with value my-value. The body is a JSON string. Notice that we used r#"... "# to write a raw string, which avoids escaping the inner double quotes. The response will include all three headers along with the status 200 and the JSON body.
A common mistake is to try to insert a header with a key that is not a valid header name or a value that contains invalid characters. Axum's parse() on the value will return an error, and unwrap() will panic. In a real application you would handle that error gracefully, but for learning examples unwrap() is acceptable because the strings are hardcoded and known to be valid.
Header Validation:
HTTP header values cannot contain newline characters or certain control characters. If you build headers from user input, always use HeaderValue::try_from instead of parse().unwrap() to avoid panics and handle errors properly.
Using Different Status Codes
The status code in the tuple can be any StatusCode variant. This lets you return meaningful responses like 201 Created for a successful resource creation or 404 Not Found for a missing item.
use axum::{
http::{header, HeaderMap, StatusCode},
body::Body,
routing::get,
Router,
};
async fn not_found_response() -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
(
StatusCode::NOT_FOUND,
headers,
Body::from("Sorry, that page does not exist."),
)
}
async fn created_response() -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
headers.insert(header::LOCATION, "/new-resource".parse().unwrap());
(
StatusCode::CREATED,
headers,
Body::from(r#"{"id":42,"status":"created"}"#),
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/missing", get(not_found_response))
.route("/create", get(created_response));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The first handler returns a 404 Not Found with a simple text body. The second returns a 201 Created with a JSON body and a Location header pointing to the newly created resource. Both handlers use the same tuple structure but change the status code and headers to match the situation. This is exactly why the tuple is so useful: you can adapt every part of the response depending on what happened in your handler.
Building the HeaderMap and Body Conditionally
In real handlers, you rarely hardcode all three parts. More often you build them based on some condition. You can create an empty HeaderMap and Body first, then fill them in depending on logic inside the handler.
use axum::{
http::{header, HeaderMap, StatusCode},
body::Body,
extract::Path,
routing::get,
Router,
};
async fn user_response(Path(user_id): Path<u32>) -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
// Simulate looking up a user from a database
if user_id == 1 {
(
StatusCode::OK,
headers,
Body::from(r#"{"id":1,"name":"Alice"}"#),
)
} else {
headers.insert("X-Error", "user not found".parse().unwrap());
(
StatusCode::NOT_FOUND,
headers,
Body::from(r#"{"error":"User not found"}"#),
)
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{user_id}", get(user_response));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
This handler extracts the user_id from the URL path. If the ID is 1, it returns a success response with user data. Otherwise it adds an extra error header and returns a 404 with an error message. Notice that we reuse the same headers map in both branches. We also call headers.insert again in the error branch to add a custom header only for that case. The body is created inside each tuple, so it can be different each time.
One subtle point: we need to make headers mutable before the if statement, which we do with let mut headers = .... In the error branch we use headers.insert again, which works because the map is still mutable. The tuple we return takes ownership of headers, so after one branch returns, the function exits and the map is no longer accessible. If you tried to use headers after returning, the compiler would give an error.
Body Variants: Strings, Bytes, and Empty
The Body type can be created from many different inputs. You have seen Body::from("some string") and Body::from(r#"..."#). You can also use Body::from(vec![1,2,3]) to send raw bytes, or Body::empty() to send no body at all (useful with status codes like 204 No Content).
use axum::{
http::{header, HeaderMap, StatusCode},
body::Body,
routing::get,
Router,
};
async fn empty_body_response() -> (StatusCode, HeaderMap, Body) {
let headers = HeaderMap::new();
(StatusCode::NO_CONTENT, headers, Body::empty())
}
async fn bytes_body_response() -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "application/octet-stream".parse().unwrap());
let data = vec![0, 1, 2, 3, 4, 5];
(StatusCode::OK, headers, Body::from(data))
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/empty", get(empty_body_response))
.route("/bytes", get(bytes_body_response));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The first handler returns 204 No Content with no body. The second returns a binary body from a Vec<u8>. The Content-Type header tells the client that the data is raw binary (application/octet-stream). This is exactly what you would use for serving files or binary data.
Body Ownership:
When you pass a Vec<u8> or String to Body::from, the data is moved into the body. You cannot use the original variable afterwards. If you need to reuse the data, clone it first or pass a reference that implements Into<Body>.
A Complete Example with All Three Parts Varied
Let's put everything together in one handler that changes all three parts based on a query parameter. This simulates a real endpoint that might return different statuses, headers, and bodies depending on input.
use axum::{
http::{header, HeaderMap, StatusCode},
body::Body,
extract::Query,
routing::get,
Router,
};
use std::collections::HashMap;
async fn flexible_response(Query(params): Query<HashMap<String, String>>) -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
if params.contains_key("json") {
headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
return (
StatusCode::OK,
headers,
Body::from(r#"{"result":"json"}"#),
);
}
headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
if let Some(name) = params.get("name") {
(
StatusCode::OK,
headers,
Body::from(format!("Hello, {}!", name)),
)
} else {
(
StatusCode::BAD_REQUEST,
headers,
Body::from("Missing 'name' query parameter"),
)
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(flexible_response));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
This handler reads the query string using Query<HashMap<String, String>>. If the query contains a json key at all, for example ?json=true, it returns a JSON response. Otherwise it looks for a name parameter. If name exists, it returns a greeting. If neither condition is met, it returns a 400 Bad Request with a text explanation. Notice how each branch builds a different tuple, and some branches add extra headers or change the status. This is a realistic pattern for an API endpoint that needs fine-grained control over the response.
Common Beginner Mistakes
Even though the tuple is straightforward, there are a few traps that catch people off guard.
Forgetting Mutability on HeaderMap:
If you write let headers = HeaderMap::new(); without mut, then try headers.insert(...), the compiler will complain that you cannot mutate an immutable variable. Always use let mut headers = HeaderMap::new(); when you plan to add headers.
Incorrect Content-Type for Body:
If you return JSON data but forget to set Content-Type to application/json, many HTTP clients will treat the body as plain text. This can break APIs that expect JSON. Always set the correct Content-Type header when the body format matters.
HeaderMap is Not Order-Sensitive:
Headers in an HTTP response do not have a guaranteed order from the client's perspective. The order you insert them into the HeaderMap may or may not be preserved. Do not rely on header order for correctness.
Another mistake is trying to return a (StatusCode, HeaderMap, Body) when the Body you created has a lifetime that ends before the response is sent. This can happen if you borrow data inside the handler and try to put it into the body. For example, if you create a String inside the handler and then pass a reference to it into Body::from, the reference would become invalid when the handler returns. Instead, always move owned data into Body::from using Body::from(owned_string) or Body::from(owned_vec).
When to Use This Tuple vs. Other Approaches
Axum gives you many ways to return a response. You might wonder when to use (StatusCode, HeaderMap, Body) instead of a simpler tuple like (StatusCode, String) or a manual Response::builder. The answer is about how much control you need.
- If you only need to change the status code and keep default headers and a text body,
(StatusCode, String)is shorter. - If you need to set custom headers and a string body,
(HeaderMap, String)works well. - If you need to set status, headers, and a non-string body (like binary or empty), or if you want to build the body from a more complex source, this triple tuple is the right choice. It gives you complete control without dropping to the lower-level
Responseobject.
The triple tuple is also useful when the body may be empty and you want to avoid creating a String that is empty. Body::empty() is more explicit and avoids unnecessary allocation.
Summary
Returning (StatusCode, HeaderMap, Body) from a handler is the most direct way to send a fully customized HTTP response in Axum. You set the status code to communicate success, failure, or redirection. You build a HeaderMap to include content type, caching directives, custom headers, and more. You create a Body from a string, bytes, or nothing to deliver the actual payload. Together, these three parts form a complete response that you control piece by piece.
The key insight is that Axum treats this tuple as a recipe: build the response from the Body, merge the HeaderMap, then apply the StatusCode last. There is no magic beyond that. Once you understand how to build each part, you can construct any HTTP response your application needs.
If you find yourself needing even more control - like setting response extensions or streaming body data - you can explore manual response construction, but for most cases where you want to explicitly set status, headers, and body, this tuple is the ideal tool.