Learn Axum · 4/13

Responses: Replying to the Client

7 min read

Welcome back, fellow Rustacean! 🦀

In the previous chapters, we learned how to listen to requests. We learned how to extract data, read paths, and parse JSON bodies. Basically, we learned how to be good listeners. But a server that only listens is about as useful as a brick wall.

It is time to talk back.

In this module, we are covering Responses. We will look at how Axum transforms your Rust code into HTTP responses that browsers and API clients can understand.


1. The IntoResponse Trait: Understanding Axum Output

The Definition

IntoResponse is a Rust trait provided by Axum. Any type that implements this trait can be returned from a handler function. It dictates how a specific Rust type is converted into an HTTP response (containing a status code, headers, and a body).

The Problem

Rust is a statically typed language. Your functions might return a String, a Vec<u8>, a Json<struct>, or a Result. However, the HTTP protocol doesn't care about your Rust types; it expects a standardized HTTP Response message (text/bytes).

Without a standardized system, you would have to manually construct a raw HTTP response string like HTTP/1.1 200 OK\r\n... every single time you wrote a function. That is tedious and prone to error.

The Solution

Axum uses the IntoResponse trait as a contract. If your type implements it, Axum knows exactly how to convert it into an HTTP response.

Axum provides default implementations for most common types:

  • String / &str → text/plain body with 200 OK.
  • Vec<u8> → application/octet-stream body with 200 OK.
  • () (Unit type) → Empty body with 200 OK.
  • Json<T> → application/json body.

Practical Example

Here is the simplest way to return data. You don't need to wrap it in anything fancy if it's just text.

rust
use axum::{
    routing::get,
    Router,
    response::IntoResponse,
};

// Handlers usually return "impl IntoResponse" to be flexible
async fn plain_text() -> impl IntoResponse {
    "Hello! I am a plain string."
}

async fn pure_html() -> impl IntoResponse {
    // Axum treats this as text/plain by default unless we set headers (more on that later), 
    // but browsers are smart enough to render it often. 
    // However, explicit HTML types exist in other crates.
    "<h1>I am a big header</h1>"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/text", get(plain_text))
        .route("/html", get(pure_html));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("Server running on port 3000");
    axum::serve(listener, app).await.unwrap();
}

Industry Tip: In production, you almost always return impl IntoResponse. This allows you to change the underlying return type (e.g., swapping a String for a Json struct) without breaking the function signature in the trait definition.


2. Sending JSON: Serializing Rust Structs

The Definition

JSON Serialization is the process of converting a Rust data structure (like a struct or enum) into a JSON string format that can be sent over the network.

The Problem

You have a Rust struct representing a User:

rust
struct User {
    id: u32,
    username: String
}

You cannot send this struct directly over the wire because the client (JavaScript, cURL, Mobile App) doesn't know what a Rust struct is. They speak JSON. Manually formatting a string like format!("{{\"id\": {}, ...}}", user.id) is a nightmare, insecure, and leads to insanity.

The Solution

We use Serde. Serde is the de facto standard serialization framework for Rust. Axum provides a wrapper type axum::Json that, when combined with Serde, automatically converts your struct into valid JSON and sets the Content-Type: application/json header for you.

Practical Example

First, you must add serde to your Cargo.toml. This is the step 90% of beginners forget and then wonder why the compiler is yelling at them.

toml
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] } # Essential!
serde_json = "1"

Now, the code:

rust
use axum::{
    routing::get,
    Json, // The wrapper
    Router,
    response::IntoResponse,
};
use serde::Serialize; // The trait for converting struct -> string

// 1. Derive Serialize so Serde can chop this up into JSON
#[derive(Serialize)]
struct User {
    id: u64,
    username: String,
    email: String,
    is_active: bool,
}

// 2. Wrap the return type in Json<T>
async fn get_user() -> impl IntoResponse {
    let user = User {
        id: 1337,
        username: "rusty_crab".to_string(),
        email: "[email protected]".to_string(),
        is_active: true,
    };

    // This converts the struct to '{"id":1337, ...}' 
    // and sets header 'content-type: application/json'
    Json(user)
}

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

Fun Fact: If you try to return Json(user) without #[derive(Serialize)] on the struct, the compiler error will look terrifying. It usually means "I don't know how to turn this memory chunk into text." Always check your derives!


3. Status Codes: Controlling HTTP Response Codes

The Definition

HTTP Status Codes are three-digit integers that indicate the result of the request (e.g., 200 for Success, 404 for Not Found, 500 for Server Explosion).

The Problem

By default, if you just return a String or JSON, Axum assumes everything is fine and sends a 200 OK.
But what if the user asks for item ID 99, and it doesn't exist? Returning "Item not found" with a 200 OK status is an architectural sin. It confuses frontend logic and API clients.

The Solution

Axum's IntoResponse implementation for Tuples.
Axum allows you to return a tuple in the format: (StatusCode, Body).

Practical Example

rust
use axum::{
    http::StatusCode,
    routing::get,
    Json,
    Router,
    response::IntoResponse,
};
use serde::Serialize;

#[derive(Serialize)]
struct ErrorMessage {
    error: String,
}

async fn create_item() -> impl IntoResponse {
    // Successfully created something? Use 201 Created.
    (StatusCode::CREATED, "Item created successfully")
}

async fn check_permission() -> impl IntoResponse {
    // Not allowed? Use 401 Unauthorized or 403 Forbidden.
    (StatusCode::UNAUTHORIZED, "You shall not pass!")
}

// You can mix Status Codes with JSON too!
async fn get_missing_item() -> impl IntoResponse {
    let error_response = ErrorMessage {
        error: "Item 404 not found in database".to_string(),
    };

    // Return (Status, JsonWrapper)
    (StatusCode::NOT_FOUND, Json(error_response))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/create", get(create_item))
        .route("/hidden", get(check_permission))
        .route("/item", get(get_missing_item));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Under the Hood: When you return (StatusCode, Body), Axum creates a response object, sets the status code on it, and then puts the body inside. It's syntactic sugar to avoid you having to build the response object manually.


4. Custom Headers: Setting Response Headers Explicitly

The Definition

HTTP Headers are key-value pairs sent in the response that provide metadata. Examples include Set-Cookie, Cache-Control, or custom API headers like x-request-id.

The Problem

Sometimes you need to tell the browser strictly not to cache a response, or you need to send back an authentication token. Simply returning the body isn't enough; you need to attach metadata to the envelope.

The Solution

Just like with Status Codes, Axum uses Tuples or Response builders to append headers.
The tuple pattern extends to: (StatusCode, Headers, Body) or just (Headers, Body).

Practical Example

We will use the HeaderMap for robust header management, or an array of tuples for simple cases.

rust
use axum::{
    http::{HeaderMap, HeaderValue, StatusCode, header},
    routing::get,
    Router,
    response::IntoResponse,
};

async fn custom_headers() -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    
    // Standard headers (using constants prevents typos)
    headers.insert(
        header::CACHE_CONTROL, 
        HeaderValue::from_static("no-cache, no-store")
    );

    // Custom headers
    headers.insert(
        "x-server-mood", 
        HeaderValue::from_static("happy")
    );

    // Order: (Status, Headers, Body)
    (StatusCode::OK, headers, "I have custom headers!")
}

// The "Lazy" way using an array of tuples for simple headers
async fn simple_headers() -> impl IntoResponse {
    (
        [
            ("x-foo", "bar"),
            ("x-baz", "qux"),
        ],
        "I also have headers, but less typing."
    )
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/headers", get(custom_headers))
        .route("/simple", get(simple_headers));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Industry Standard: When defining custom headers, always prefix them with x- (e.g., x-api-version), although this standard is slowly being relaxed. More importantly, always use the constants in axum::http::header (like CONTENT_TYPE) instead of typing strings manually. "content-type" and "Content-Type" are the same, but "Contet-Type" will cost you 3 hours of debugging.


Summary

You now possess the power to speak! 🗣️

  1. IntoResponse: The magic trait that lets you return strings, bytes, and tuples directly.
  2. JSON: Wrap structs in Json(T) and ensure you derived Serialize.
  3. Status Codes: Use tuples (StatusCode, Body) to tell the client if they succeeded or failed.
  4. Headers: Use tuples (HeaderMap, Body) to add metadata like caching rules.

📚 References & Further Reading

Challenge

You are given an array of user objects. Each object contains an id, name, email, isActive status, and age.

Write a function named processUserData that accepts one argument: an array of user objects.

Your function must perform the following actions sequentially:

  1. Filter out any user whose isActive property is false.
  2. For the remaining active users, create a new array of strings. Each string must be formatted as: "[name] ([age])".
  3. Sort this new array of strings alphabetically by the user's name in ascending order.
  4. Return the final sorted array of strings.

Expected result

Your code should define a single function processUserData.

When this function is invoked with the provided userData array, it must return the following JavaScript array:

json
[
  "Alice Williams (25)",
  "John Doe (32)",
  "Peter Jones (45)"
]

The implementation should correctly use array manipulation methods to filter, map, and sort the data according to the requirements.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.