IntoResponse trait
Understand how Axum turns handler return values into HTTP responses using the IntoResponse trait, with beginner-friendly examples and common implementation patterns
When you write an Axum handler, the return value is not yet an actual HTTP response. It is a Rust value that Axum must convert into bytes on the wire, with a status code, headers, and a body. The mechanism that performs this conversion is the IntoResponse trait.
This page explains what IntoResponse is, why Axum needs it, how it works behind the scenes, and how to think about it as a beginner. By the end, you will be able to look at any Axum handler signature and understand exactly what happens to its return value, and you will be ready to implement the trait for your own custom types.
What an HTTP response actually is
Before diving into the trait, you need a clear picture of what a web server sends back to a browser or HTTP client.
An HTTP response has three parts:
- A status line containing the protocol version and a status code like
200 OKor404 Not Found. - Headers containing metadata as key-value pairs. Common examples are
content-type: text/plainandcontent-length: 42. - A body containing the actual data as raw bytes.
When a browser requests https://example.com/hello, the server might respond with something like this, simplified for clarity:
HTTP/1.1 200 OK
content-type: text/plain
content-length: 12
Hello world
The status line, headers, and body together form the complete HTTP response. Rust web frameworks need a way for your handler code to produce all three of these pieces without making you assemble the raw bytes manually every time.
The problem IntoResponse solves
Handlers in Axum are Rust functions. A function can return a String, a StatusCode, a custom struct, or many other things. Axum has no idea how to turn an arbitrary Rust type into an HTTP response unless every type tells it how.
The straightforward approach would be to require every handler to return a fully assembled Response object with all three parts already filled in. That works, but it is verbose. Returning plain text would look like this:
use axum::{
body::Body,
http::StatusCode,
response::Response,
};
async fn handler() -> Response {
Response::builder()
.status(StatusCode::OK)
.header("content-type", "text/plain")
.body(Body::from("Hello world"))
.unwrap()
}
That is a lot of boilerplate for the most common case. You would have to write it in every handler. Axum avoids this by asking one question: can this type turn itself into a Response?
If the answer is yes, the type implements IntoResponse. Axum then automatically calls the conversion for you after your handler runs.
What IntoResponse is
IntoResponse is a Rust trait defined by Axum. A trait is a contract that says a type must provide certain methods. In this case, the contract has one method:
fn into_response(self) -> Response;
The method consumes the value, meaning it takes ownership of it, and produces a Response. The Response type here comes from the http crate that Axum re-exports as axum::response::Response.
For a beginner, the mental model is simple: IntoResponse is a promise that a value knows how to become an HTTP response. When your handler returns a value, Axum sees that the value implements this promise, calls into_response() on it, and uses the resulting Response to send data back to the client.
Why the name starts with Into:
Rust has a naming convention for traits that consume values and turn them into another type. Into<T> converts a value into T. IntoResponse follows the same pattern: it converts a value into a Response. The prefix Into tells you the direction of conversion.
How Axum uses the trait in handlers
When you define a handler, the return type must implement IntoResponse. Axum cannot accept a handler whose return type does not satisfy this requirement.
Consider the simplest possible handler:
use axum::response::IntoResponse;
async fn hello() -> &'static str {
"Hello, world!"
}
The string literal "Hello, world!" has the type &'static str. Axum checks at compile time whether &'static str implements IntoResponse. It does, so the handler is valid.
When a request arrives, Axum calls the handler, receives the &'static str value, and then calls into_response() on it. The implementation for &'static str creates a Response with status 200 OK, a content-type: text/plain; charset=utf-8 header, and the string bytes as the body.
You do not see any of this conversion code. It happens inside Axum after your handler returns.
Compile-time enforcement:
Axum checks handler return types at compile time, not at runtime. If you try to return a type that does not implement IntoResponse, the Rust compiler will reject your program with an error. This is a good thing: you cannot accidentally ship a handler that returns something Axum cannot turn into a response.
The starter example in full
Here is a complete runnable Axum application using a single handler that returns a &'static str:
use axum::{
routing::get,
Router,
};
#[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();
}
async fn hello() -> &'static str {
"Hello, world!"
}
Run this with cargo run and open http://127.0.0.1:3000 in a browser. You will see the text Hello, world! on a blank page. If you inspect the network response using browser developer tools, you will see 200 OK as the status and content-type: text/plain; charset=utf-8 as a header.
That is IntoResponse in action. You returned a string slice, and Axum used its IntoResponse implementation to build the full HTTP response for you.
Everything is working if you see this:
When your handler compiles and you see the expected text in the browser, the IntoResponse conversion has succeeded. The fact that you never had to write Response::builder() or set headers manually is the trait doing its job silently.
How IntoResponse is implemented for common types
Axum provides IntoResponse implementations for many built-in Rust and Axum types. You will use these implementations constantly, even if you never think about them explicitly.
&'static str
A string literal has the type &'static str, and Axum implements IntoResponse for it. The implementation sets the status to 200 OK, the content-type header to text/plain; charset=utf-8, and uses the string bytes as the body.
The 'static lifetime means the string lives for the entire program. This is required because the response body might be sent after the handler returns, and the bytes must still be valid.
String
An owned String also implements IntoResponse. The behavior is identical to &'static str, but it works with heap-allocated strings that you build at runtime:
async fn hello() -> String {
let name = "Axum";
format!("Hello, {name}!")
}
This handler builds a new String on the heap and returns it. Axum converts that String into a Response with the same text response behavior as &'static str.
StatusCode
A StatusCode alone implements IntoResponse. Returning only a status code produces an empty body with that status:
use axum::http::StatusCode;
async fn not_found() -> StatusCode {
StatusCode::NOT_FOUND
}
The resulting response has status 404 Not Found, an empty body, and no custom content-type header. This is useful when you want to signal success or failure without returning any content.
Response
The Response type from the http crate also implements IntoResponse by returning itself unchanged. The into_response method for Response is effectively an identity function:
use axum::{
body::Body,
http::StatusCode,
response::Response,
};
async fn custom() -> Response {
Response::builder()
.status(StatusCode::CREATED)
.header("x-custom-header", "hello")
.body(Body::from("Resource created"))
.unwrap()
}
Because Response already is an HTTP response, the conversion is trivial. Axum can accept handlers that return fully assembled responses alongside handlers that return simpler types.
Import Response from axum::response:
The Response type in these examples comes from axum::response::Response, which is the http::Response type already filled in with Axum's body type. Do not import it as axum::http::Response: that is the generic http::Response<T> with no body type chosen, so using it bare as a return type fails to compile with missing generics for struct Response.
Option<T> is not a response type
Unlike in some other frameworks, Axum 0.8 does not implement IntoResponse for Option<T>. A handler that returns Option<&'static str> will not compile: the compiler reports that the handler trait is not satisfied, because Option<T> implements IntoResponseParts (so an Option<HeaderMap> can appear as a part inside a response tuple, where None simply leaves the response unchanged), not IntoResponse itself.
If a handler may or may not have data to return, express that with Result or by matching explicitly:
use axum::http::StatusCode;
async fn maybe_user(found: bool) -> (StatusCode, &'static str) {
if found {
(StatusCode::OK, "User found")
} else {
(StatusCode::NOT_FOUND, "User not found")
}
}
Returning None does not produce a 404 Not Found response on its own. You have to choose the status code yourself, as above, or return a Result whose error type maps to 404.
Result<T, E>
When both T and E implement IntoResponse, Result<T, E> also implements it. An Ok(value) converts the inner success value. An Err(error) converts the inner error value.
This is the foundation of error handling in Axum, but for this page it is enough to know that Result works as a response type because both arms implement IntoResponse.
Implementing IntoResponse for your own type
The real power of the trait appears when you implement it for your own structs or enums. You can define a type that represents a domain-specific response and then control exactly how it maps to an HTTP response.
A basic custom implementation
Suppose you have an API that returns user information. Instead of returning a raw String, you want a dedicated type:
use axum::{
body::Body,
http::StatusCode,
response::{IntoResponse, Response},
};
struct User {
id: u64,
name: String,
}
impl IntoResponse for User {
fn into_response(self) -> Response {
let body_text = format!("User {}: {}", self.id, self.name);
Response::builder()
.status(StatusCode::OK)
.header("content-type", "text/plain; charset=utf-8")
.body(Body::from(body_text))
.unwrap()
}
}
async fn get_user() -> User {
User {
id: 42,
name: "Alice".to_string(),
}
}
Now your handler returns a User, and the trait implementation controls the response. The into_response method formats the struct fields into a text body, sets the appropriate status and content type, and returns a Response.
This approach keeps your handlers clean. Instead of every handler that deals with users having to know how to format user data as an HTTP response, the User type itself owns that knowledge.
Why a custom implementation is useful
Imagine you have ten handlers that return users. Without a custom IntoResponse implementation, each handler would need to convert a User into a Response manually. Any change to the response format, such as adding a new header or changing the status code, would require updating all ten handlers.
With a custom implementation, the conversion logic lives in one place. When the response format changes, you update the into_response method once, and every handler that returns User automatically picks up the change.
This is the same principle as any function or abstraction: centralize logic that would otherwise be duplicated.
Custom implementations are common in real projects:
Production Axum applications often define custom error types and custom response types that implement IntoResponse. This is not an advanced feature reserved for edge cases. It is a normal, everyday pattern that keeps response logic consistent across an application.
How the trait composes with tuples
Axum provides IntoResponse implementations for tuples of response parts. This lets you combine a status code, headers, and a body into a single return value without manually building a Response.
(StatusCode, &'static str)
Returning a status code along with a string body is a common pattern:
use axum::http::StatusCode;
async fn created() -> (StatusCode, &'static str) {
(StatusCode::CREATED, "Resource created successfully")
}
The tuple implements IntoResponse by converting each part and merging them. The status code becomes the response status, and the string becomes the body with a default text content type.
(StatusCode, String)
If you need a dynamic string body rather than a literal, use String:
use axum::http::StatusCode;
async fn created_with_name() -> (StatusCode, String) {
let name = "Axum";
(StatusCode::CREATED, format!("Created {name}"))
}
(StatusCode, HeaderMap, Body)
For full control over status, headers, and body, combine all three:
use axum::{
body::Body,
http::{header, HeaderMap, StatusCode},
};
async fn full_control() -> (StatusCode, HeaderMap, Body) {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
(StatusCode::OK, headers, Body::from("Custom headers and body"))
}
This tuple form is a middle ground between returning a bare value and returning a fully assembled Response. You get explicit control over each part without needing to call Response::builder().
The trait's relationship to Response
Response is the final destination for every conversion. When Axum calls into_response(), the result is always a value of type Response. That value is then written to the network connection.
Think of IntoResponse as an adapter. The Response type is the standardized format that the HTTP layer understands. IntoResponse adapts various Rust types into that standardized format.
This separation matters because it allows the HTTP layer to remain generic. It only ever deals with Response objects. It does not need to know whether the original handler returned a String, a StatusCode, a User, or anything else. The trait erases those differences by converting everything into the same type.
A mental model for beginners
The easiest way to think about IntoResponse is to compare it to a universal power adapter.
Imagine you have a power outlet that accepts only one specific plug shape. That outlet is the HTTP layer, and the specific plug shape is the Response type. Your electronic devices have many different plug shapes: a string is one shape, a status code is another, your custom User type is yet another.
IntoResponse is the adapter that converts any device's plug into the shape the outlet accepts. Each device type comes with its own adapter that knows how to convert its specific shape. When you plug a device in, you use its adapter, and the outlet never needs to know what the original shape was.
Axum works the same way. It knows how to write Response objects to the network. Your job is to make sure every handler return type has an adapter, an IntoResponse implementation, that converts it into a Response.
What happens when no implementation exists
If you return a type that does not implement IntoResponse, the compiler rejects your handler.
Consider a struct with no IntoResponse implementation, registered as a handler:
use axum::{routing::get, Router};
struct NotAResponse {
value: i32,
}
async fn broken_handler() -> NotAResponse {
NotAResponse { value: 10 }
}
let app = Router::new().route("/", get(broken_handler));
When you try to compile this, you get an error similar to:
error[E0277]: the trait bound `fn() -> impl Future<Output = NotAResponse> {broken_handler}: Handler<_, _>` is not satisfied
The compiler is saying the function cannot be used as a handler, because its return type does not implement IntoResponse. Either implement IntoResponse for NotAResponse, or return a type that already implements it.
A missing implementation stops compilation entirely:
A handler with a return type that lacks IntoResponse will not compile at all. This is not a runtime warning that you can ignore. The entire application fails to build until you fix the handler or add an implementation.
Common mistakes beginners make
Several mistakes show up frequently when people first work with IntoResponse.
Returning a string literal without understanding lifetimes
A string literal like "hello" works as a handler return value because it has type &'static str. If you try to return a borrowed string slice that does not live for the whole program, you will run into lifetime errors:
async fn broken() -> &str {
let s = String::from("hello");
&s // error: borrowed value does not live long enough
}
The local String is dropped when the function returns, so the reference &s would point to invalid memory. Return an owned String instead:
async fn fixed() -> String {
let s = String::from("hello");
s
}
Forgetting that into_response consumes the value
The method signature is fn into_response(self) -> Response. It takes self, not &self, which means the value is moved into the method and cannot be used afterward.
In practice this rarely matters in handlers, because the return value is consumed anyway. But when implementing the trait for a type that holds data you need later, remember that the method takes ownership.
Overcomplicating simple responses
Beginners sometimes build a full Response with Response::builder() for every handler, even when returning a simple &'static str or String would work fine.
If the built-in implementation gives you the status, headers, and body you need, use it. Reserve manual Response construction for cases where the built-in implementations are not sufficient, such as when you need a non-standard status code combined with custom headers.
Assuming all response types set content-type automatically
Not all IntoResponse implementations set a content-type header. A bare StatusCode does not set one. A String does. A custom implementation sets only whatever you tell it to set.
When your client receives a response without the expected content type, check whether the type you returned actually sets that header in its IntoResponse implementation.
Implementing IntoResponse for custom error types
A common real-world use of the trait is creating a dedicated error type that can be returned from handlers. This centralizes error-to-response conversion.
Here is a complete pattern you might see in an Axum application:
use axum::{
body::Body,
extract::Path,
http::StatusCode,
response::{IntoResponse, Response},
};
enum ApiError {
NotFound,
InvalidInput,
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, message) = match self {
ApiError::NotFound => (StatusCode::NOT_FOUND, "Resource not found"),
ApiError::InvalidInput => (StatusCode::BAD_REQUEST, "Invalid input"),
};
(status, message).into_response()
}
}
async fn get_item(Path(id): Path<u64>) -> Result<&'static str, ApiError> {
if id == 0 {
Err(ApiError::InvalidInput)
} else if id == 999 {
Err(ApiError::NotFound)
} else {
Ok("Item data")
}
}
The ApiError type maps each variant to a status code and message. The into_response method builds a tuple (StatusCode, &'static str) and delegates to that tuple's existing IntoResponse implementation. This is a clean way to reuse built-in conversions inside your custom one.
The handler returns Result<&'static str, ApiError>. Because both &'static str and ApiError implement IntoResponse, the Result type automatically implements it too.
Delegating to built-in conversions is idiomatic:
When implementing IntoResponse for your own type, check whether you can compose existing implementations. Tuples, StatusCode, and String already handle the low-level details. Reusing them keeps your custom implementation small and consistent with Axum's defaults.
The relationship between IntoResponse and Response::builder
You have now seen two ways to produce a Response:
- Directly using
Response::builder().status(...).header(...).body(...). - Indirectly by returning a type that implements
IntoResponse.
Both end up producing the same Response type. The difference is where the conversion happens.
With Response::builder(), you perform the conversion explicitly in your handler. You control every detail at the call site.
With IntoResponse, the conversion is delegated to the type's implementation. You return a simpler type, and the trait logic runs after your handler finishes.
There is no strict rule about which approach to use. In general, use IntoResponse for responses that fit the built-in implementations or your custom types. Use Response::builder() for one-off responses where building the response inline is clearer than creating a dedicated type.
A practical walkthrough from simple to custom
Let us trace a single scenario through three levels of complexity to see the progression.
Level 1: Use a built-in type
You need a handler that returns plain text:
async fn text_handler() -> &'static str {
"Plain text response"
}
This works with no extra code. Axum's built-in implementation for &'static str handles everything.
Level 2: Use a tuple
You need a handler that returns text with a specific status code:
use axum::http::StatusCode;
async fn text_with_status() -> (StatusCode, &'static str) {
(StatusCode::ACCEPTED, "Request accepted")
}
The tuple combines two built-in implementations. Still no custom code needed.
Level 3: Use a custom type
You need a handler that returns structured data with a specific format and headers:
use axum::{
body::Body,
http::StatusCode,
response::{IntoResponse, Response},
};
struct Report {
title: String,
rows: Vec<String>,
}
impl IntoResponse for Report {
fn into_response(self) -> Response {
let body_text = format!(
"Report: {}\nRows:\n{}",
self.title,
self.rows.join("\n")
);
Response::builder()
.status(StatusCode::OK)
.header("content-type", "text/plain; charset=utf-8")
.header("x-report-title", self.title)
.body(Body::from(body_text))
.unwrap()
}
}
async fn report_handler() -> Report {
Report {
title: "Daily numbers".to_string(),
rows: vec!["10".to_string(), "20".to_string(), "30".to_string()],
}
}
Now the response format is centralized in the Report type. Any handler that returns a Report gets the same formatting, headers, and status automatically.
Summary
IntoResponse is the bridge between your handler's return value and the HTTP response that Axum sends to the client. It works by having every returnable type know how to convert itself into a Response.
The trait matters because it removes boilerplate. You can return a plain string, a status code, a tuple, or your own struct, and Axum handles the conversion. When the built-in conversions are not enough, you implement the trait yourself, which centralizes your response logic and keeps handlers readable.
The most important insight is that Axum validates response conversions at compile time. You cannot accidentally return a type that Axum cannot turn into a response. The compiler catches the mistake before your program ever runs. This gives you confidence that every handler in your application produces a valid HTTP response.
The next step after understanding IntoResponse is to explore the specific built-in types that implement it, starting with the simplest text-based responses and moving toward more structured formats.