Response::builder in Axum
Learn how to manually construct HTTP responses in Axum using Response::builder, with examples for status codes, headers, and bodies.
In Axum, most of the time you can return simple types from a handler - a string, a status code, a JSON value, or a tuple of those. The framework automatically turns them into a proper HTTP response. But sometimes you need full control over every part of the response: the exact status code, a custom set of headers, a specific body format. That's where Response::builder comes in.
Response::builder is a low-level tool that lets you assemble an HTTP response piece by piece. It comes from the http crate, which Axum re-exports. You don't need to add http as a separate dependency; it's already part of Axum.
What Is an HTTP Response, Really?
Before diving into the builder, it helps to know what a response actually contains. When a browser makes a request to your server, your server sends back three things:
- A status code - a number like 200 for "OK", 404 for "Not Found", or 500 for "Internal Server Error".
- Headers - key-value pairs of metadata, like
Content-Type: text/htmlor a customX-Request-ID: abc123. - A body - the actual content, which can be text, JSON, binary data, or nothing at all.
Response::builder gives you a way to set each of these three parts explicitly. You start with an empty builder, add a status code, add headers, and finally attach a body. When you call body(...), you get back a Response object that your handler can return.
When Do You Need Response::builder?
You don't need it for every response. Axum already provides convenient wrapper types like Json, Html, StatusCode, and tuples like (StatusCode, String). Those cover the vast majority of cases.
But there are situations where the built-in types feel awkward:
- You want to set several custom headers at once.
- You need to decide between multiple status codes based on logic inside the handler.
- You want to build a response incrementally, perhaps in a helper function that returns a
Responsedirectly.
Response::builder is the escape hatch for those times. It's not the first tool you reach for, but it's the one that never says "you can't do that".
Low-Level vs High-Level:
Think of built-in types as pre-made sandwiches. Response::builder is the kitchen. You can still make any sandwich you like, but you have to assemble the bread, filling, and condiments yourself.
A Simple First Example
Let's start with the smallest possible handler that uses Response::builder. It returns a plain text response with status 200. The examples on this page use this Cargo.toml:
# Cargo.toml
[package]
name = "response-builder-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
serde_json is only needed for the one comparison example near the end that builds a JSON value with the json! macro. Everything else uses axum and tokio alone.
use axum::{
body::Body,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn hello() -> Response {
Response::builder()
.status(StatusCode::OK)
.body(Body::from("Hello, world!"))
.unwrap()
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(hello));
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();
}
Let's go through this line by line.
Response::builder()creates a new builder. It starts with default settings, a status of 200 and no headers, until you change them with the methods below..status(StatusCode::OK)sets the HTTP status to 200.StatusCodeis a struct from thehttpcrate that Axum re-exports. It wraps a 16-bit integer and has many associated constants:OK,NOT_FOUND,INTERNAL_SERVER_ERROR, and dozens more..body(Body::from("Hello, world!"))attaches the response body.Bodyis Axum's body type; it can be created from strings, bytes, or streams.Body::fromis flexible and accepts many input types..unwrap()is needed becausebody()returns aResult. We'll talk about why later, but for now, in this simple case it always succeeds.
If you run this server and open http://127.0.0.1:3000 in your browser, you'll see the text "Hello, world!".
If You See the Text, It Works:
When you build a response successfully and the handler compiles, the builder worked correctly. The unwrap() will only panic if you did something invalid, like setting a header with a bad value. For a plain body with a normal status, it's fine.
Building a Response Without .unwrap()
Using .unwrap() in a handler is acceptable for quick examples, but in production code you should handle the possibility of failure properly. The body() method returns a Result<Response, http::Error>. That error can happen if a header value you set earlier contains invalid characters, for example.
A better approach is to return a Result from the handler. Axum knows how to turn a Result<Response, SomeError> into a response, as long as the error type implements IntoResponse. StatusCode implements IntoResponse, so it is a natural choice: a builder failure becomes a plain status response. Note that http::Error itself does not implement IntoResponse, so you cannot use it directly as the handler's error type. Let's see a version that returns Result<Response, StatusCode>:
use axum::{
body::Body,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn hello() -> Result<Response, StatusCode> {
let response = Response::builder()
.status(StatusCode::OK)
.header("X-Custom-Header", "hello")
.body(Body::from("Hello, world!"))
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(response)
}
Notice two changes:
- The return type is now
Result<Response, StatusCode>instead of justResponse. - We replaced
.unwrap()with.map_err(...)?. The builder error is converted into a500 Internal Server Errorstatus, and the?operator returns early with that error if something goes wrong. Otherwise it gives us the successfulResponse, which we wrap inOk(...).
This is more robust because a bad header value won't crash the entire server; it will just produce an error response.
Don't Unwrap Without Thinking:
While .unwrap() is handy in small examples, the .body() call can fail if an earlier builder step stored an invalid value, and that failure will panic at runtime. The panic aborts that one request, not the whole server, but the client still gets no response at all. In production code, always prefer returning a Result and handling the error. That way a single malformed request gets a clean error response instead of a dropped connection.
Setting Status Codes
Response::builder lets you set any HTTP status code you need. The StatusCode type from http includes all the standard ones. Here are a few common ones:
StatusCode::OK→ 200StatusCode::CREATED→ 201StatusCode::NO_CONTENT→ 204StatusCode::BAD_REQUEST→ 400StatusCode::UNAUTHORIZED→ 401StatusCode::FORBIDDEN→ 403StatusCode::NOT_FOUND→ 404StatusCode::INTERNAL_SERVER_ERROR→ 500
You can also create a custom status code from a number using StatusCode::from_u16(418).unwrap(), but that's rarely needed.
Here's an example of choosing a status code based on a condition inside the handler. The id comes from the URL path, so the handler takes a Path<u64> extractor. A plain u64 parameter would not work here: handler arguments must be extractors, and a bare number is not one.
use axum::{
body::Body,
extract::Path,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn check_file(Path(id): Path<u64>) -> Response {
let status = if id == 0 {
StatusCode::BAD_REQUEST
} else if id > 100 {
StatusCode::NOT_FOUND
} else {
StatusCode::OK
};
Response::builder()
.status(status)
.body(Body::from(format!("File ID: {id}")))
.unwrap()
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/file/{id}", get(check_file));
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();
}
In this example, the status code is computed first, stored in a variable, and then passed to .status(). This pattern keeps the builder call clean and easy to read. Visiting /file/5 returns 200, /file/0 returns 400, and /file/101 returns 404.
Adding Headers
Headers are metadata about the response. They tell the browser or client how to interpret the body, whether to cache it, what server software is running, and many other things.
With Response::builder, you add headers using the .header(key, value) method. You can chain multiple .header() calls to add several headers at once.
use axum::{
body::Body,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn with_headers() -> Response {
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "text/plain; charset=utf-8")
.header("X-Powered-By", "Axum")
.header("Cache-Control", "no-store")
.body(Body::from("Response with custom headers"))
.unwrap()
}
The first header sets the content type to plain text with UTF-8 encoding. The second is a custom header often used to identify the framework. The third tells browsers not to cache this response.
Header Names Are Case-Insensitive:
HTTP header names are case-insensitive, so "content-type", "Content-Type", and "CONTENT-TYPE" all refer to the same header. However, using the conventional capitalization (first letter of each word capitalized) makes your code easier to read.
If you need to set many headers at once, build a HeaderMap first and then add it to the finished response. The builder has no method that takes a whole HeaderMap, so the map goes onto the response after .body() returns it:
use axum::{
body::Body,
http::{header, HeaderMap, StatusCode},
response::Response,
routing::get,
Router,
};
async fn with_header_map() -> Response {
let mut headers = HeaderMap::new();
headers.insert(header::SERVER, "axum".parse().unwrap());
headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
let mut response = Response::builder()
.status(StatusCode::OK)
.body(Body::from("Headers from a map"))
.unwrap();
response.headers_mut().extend(headers);
response
}
Here we use the header module from http which contains constants for standard header names. The parse().unwrap() on the value is necessary because HeaderValue enforces that the string is a valid header value (no newlines, etc.). In this case, it's safe. The headers_mut().extend(headers) call copies every entry from the map into the response's headers. Note that HeaderMap::insert replaces an existing value for a key, while the builder's .header() method appends, so a map is the right tool when you want each key to appear exactly once.
Setting the Body
The body is the actual payload of the response. Axum uses the Body type, which is a flexible wrapper around different kinds of streams. For most manual construction, you'll create a Body from a string, bytes, or an empty value.
Body::from accepts many types: String, &str, Vec<u8>, &'static [u8], and even () for an empty body. If you want to send an empty response with no content, you can use Body::empty():
use axum::{
body::Body,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn no_content() -> Response {
Response::builder()
.status(StatusCode::NO_CONTENT)
.body(Body::empty())
.unwrap()
}
For binary data, like sending an image file, you'd use Vec<u8>:
use axum::{
body::Body,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn send_image() -> Response {
let image_bytes: Vec<u8> = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; // PNG header bytes
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "image/png")
.body(Body::from(image_bytes))
.unwrap()
}
Note that setting the Content-Type header is important here; otherwise the browser might not know how to display the data.
Chaining Everything Together
The real power of Response::builder is that you can combine status, headers, and body into a single chain. The methods return the builder itself, so you can keep calling them one after another.
Here's a more realistic handler that builds a JSON error response for an API:
use axum::{
body::Body,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn api_error() -> Response {
let json_body = r#"{"error": "Something went wrong"}"#;
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header("Content-Type", "application/json")
.body(Body::from(json_body))
.unwrap()
}
This creates a response with status 500, a JSON content type, and a JSON body. The string r#"..."# is a raw string literal that makes it easy to include quotes.
Handling Errors Properly with ?
As mentioned, .body() can fail. The builder stores any error from an earlier step, such as a header value that contains a newline character, and reports it when you call .body(). Note that .header() itself does not return a Result: it returns the builder, and the failure only surfaces at .body(). Here's how you can handle that gracefully:
use axum::{
body::Body,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn safe_handler() -> Result<Response, StatusCode> {
let response = Response::builder()
.status(StatusCode::OK)
.header("X-Valid-Header", "fine")
.body(Body::from("All good"))
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(response)
}
In this handler, if the header value were invalid, the function would return early with a 500 status. Axum converts that StatusCode error into a response automatically because StatusCode implements IntoResponse.
A More Complete Example with Conditional Logic
Let's build a handler that simulates fetching a user from a database. It returns different responses based on whether the user exists, using Response::builder for each case. Like the earlier status-code example, the id comes from the URL path through a Path<u64> extractor.
use axum::{
body::Body,
extract::Path,
http::StatusCode,
response::Response,
routing::get,
Router,
};
async fn get_user(Path(id): Path<u64>) -> Response {
// Pretend we looked up the user in a database.
let user_exists = id == 1;
let user_name = if user_exists { "Alice" } else { "Unknown" };
if user_exists {
let json = format!(r#"{{"id": {}, "name": "{}"}}"#, id, user_name);
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(Body::from(json))
.unwrap()
} else {
let json = r#"{"error": "User not found"}"#;
Response::builder()
.status(StatusCode::NOT_FOUND)
.header("Content-Type", "application/json")
.body(Body::from(json))
.unwrap()
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/user/{id}", get(get_user));
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 example shows how you can build completely different responses from the same handler. The builder calls are separate, so each path sets exactly the status, headers, and body it needs. Visiting /user/1 returns {"id": 1, "name": "Alice"} with status 200, while /user/2 returns {"error": "User not found"} with status 404.
Comparing Response::builder with Built-in Types
You might wonder why you'd use Response::builder when Axum already offers so many convenient response types. The answer is control and expressiveness.
For a simple JSON response, you could write:
use axum::{Json, routing::get, Router};
use serde_json::json;
async fn simple_json() -> Json<serde_json::Value> {
Json(json!({"message": "hi"}))
}
But if you need to also set a custom header and a non-standard status code, the tuple approach might get messy:
use axum::{
http::{header, StatusCode},
response::IntoResponse,
routing::get,
Router,
};
async fn tuple_approach() -> impl IntoResponse {
(
StatusCode::CREATED,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message": "created"}"#,
)
}
That works, but as the number of headers grows, the tuple becomes harder to read. Response::builder lets you write the same thing in a way that clearly shows each part:
use axum::{
body::Body,
http::{header, StatusCode},
response::Response,
routing::get,
Router,
};
async fn builder_approach() -> Response {
Response::builder()
.status(StatusCode::CREATED)
.header(header::CONTENT_TYPE, "application/json")
.header("X-Request-Id", "abc123")
.body(Body::from(r#"{"message": "created"}"#))
.unwrap()
}
Both produce identical responses. The builder version is more verbose but also more explicit. Use whichever feels clearer for the situation.
Common Mistakes and Misconceptions
Forgetting to Call .body()
The builder will not produce a Response until you call .body(). If you try to return the builder itself, you'll get a compile error because Response::builder() returns a Builder, not a Response.
Missing Body Causes Compile Error:
The method .body() is what transforms the builder into a final Response. If you forget it, Rust will tell you that the builder type doesn't match the expected return type. Always end your chain with .body(...).
Using unwrap() Without Handling Errors
In examples it's fine, but in real code, an invalid header value or some other issue will cause a panic at runtime. That panic aborts the one request being handled: the connection is dropped without a response, but the server itself keeps running and serves the next request normally. Still, a client gets no answer at all, which is worse than a clean error response. Always prefer returning a Result and using ?.
Confusing Response with http::Response
In Axum, Response is a type alias for http::Response<Body>, defined as pub type Response<T = Body> = http::Response<T>. You can import it from axum::response::Response, which is already specialized to use Axum's Body. That is what you want for handler returns. The name axum::http::Response is the generic http::Response<T> from the http crate, which still needs a body type parameter, so axum::http::Response on its own is not a complete handler return type.
Setting the Same Header Twice Appends, It Does Not Replace
You can call .header("Content-Type", "text/plain") and then .header("Content-Type", "application/json") later. The builder does not overwrite the earlier value: each .header() call appends another value for that name, so the finished response carries two Content-Type values. A client reading the header gets both, which is almost never what you want.
If you need to replace a header, set it once, or build a HeaderMap with insert (which does replace) and add it to the response with headers_mut().extend(...), as shown in the HeaderMap example above. Be careful if you set the same header twice unintentionally, for example in a helper that adds a default header and then in handler code that adds the real one. You can see both values with get_all:
use axum::{
body::Body,
http::StatusCode,
response::Response,
};
fn main() {
let response = Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "text/plain")
.header("Content-Type", "application/json")
.body(Body::empty())
.unwrap();
let values: Vec<_> = response
.headers()
.get_all("Content-Type")
.iter()
.collect();
// values has two entries: "text/plain" and "application/json"
println!("Content-Type values: {:?}", values);
}
Trying to Set an Invalid Header Value
A header value containing a newline, carriage return, or null byte is invalid according to HTTP. The HeaderValue type used internally will reject it. If you pass a string that contains those characters, the builder stores the error and .body() returns it. That's why you need to handle the Result from .body().
Practical Real-World Scenarios
Response::builder is commonly used in middleware, error handlers, and utility functions that need to construct responses programmatically. Here are a few concrete situations:
- Custom error pages: Instead of returning a plain text 500 error, you can build a styled HTML error page with the correct status and content type.
- Security headers: You might want to add headers like
X-Content-Type-Options: nosnifforStrict-Transport-Securityto every response. A helper function usingResponse::buildercan apply these headers to a base response. - File downloads: When sending a file, you often need to set
Content-Disposition: attachment; filename="report.pdf"along with a binary body. The builder makes this straightforward. - API gateways: If you're proxying requests, you may need to copy certain headers from an upstream response while changing others. The builder gives you full control over the final response.
Builder Is Not a Performance Tool:
Using Response::builder does not make your application slower or faster. It's purely a way to construct the response object. The performance characteristics are the same as with built-in types - what matters is the actual body and headers you send.
Summary
Response::builder gives you direct, explicit control over every part of an HTTP response in Axum. You set a status code with .status(), add headers with .header() or by extending the finished response's headers from a HeaderMap, and attach a body with .body(). The builder methods can fail, so proper error handling is important.
The biggest takeaway is that Response::builder is not something you need for every handler. Use it when the convenience types feel limiting - when you need multiple custom headers, when you're constructing responses dynamically, or when you're writing utility code that must return a Response. For simple cases, sticking with String, Json, StatusCode, or tuples keeps your code shorter.
Once you understand the builder, you can construct any response Axum is capable of producing. That foundation will help when you explore more advanced topics like streaming responses or custom error handling, because those features often build on the same underlying Response type.