Returning a Status Code and Text Body with (StatusCode, String)

Learn how to return an HTTP status code together with a plain text message from Axum handlers using the (StatusCode, String) tuple, when to use it, and common mistakes beginners make.

When a web request comes in, your handler often needs to tell the client two things: what happened (the status code) and some human-readable message (the body). Axum makes this extremely convenient by letting you return a tuple containing a StatusCode and a String. The tuple (StatusCode, String) is one of the many built-in types that implement the IntoResponse trait, which means Axum knows exactly how to turn it into an HTTP response.

Before this, you may have seen handlers that return only a String or only a StatusCode. Each of those is useful on its own, but real APIs often need both. For example, when a resource is not found, you want to send 404 and a message like "User with id 42 was not found". Returning a tuple gives you that in one expression.

Starting with the Simplest Example

Let's write a tiny Axum server that has one route. When you visit any path, the handler returns 404 plus the text "Nothing here". This shows the pattern in its most basic form.

use axum::{routing::get, Router, http::StatusCode};
async fn nothing_here() -> (StatusCode, String) {
    (StatusCode::NOT_FOUND, "Nothing here".to_string())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(nothing_here));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The handler nothing_here has the return type (StatusCode, String). Inside, it builds the tuple: first the StatusCode::NOT_FOUND constant, then a String created with .to_string(). Axum will convert this tuple into an HTTP response with a 404 status line and a body containing "Nothing here".

When you run the server and send a request with curl -i http://127.0.0.1:3000/, you'll see:

HTTP/1.1 404 Not Found
content-type: text/plain; charset=utf-8
content-length: 12
date: ...
Nothing here

Everything Is Working:

If your terminal shows a 404 status and the text Nothing here, the tuple is working exactly as intended. The status code and body are both reaching the client.

Notice that Axum automatically set the Content-Type header to text/plain; charset=utf-8 because the body is a String. That's a helpful default: plain text is the most common type when you return a String.

Why the Tuple Exists

Handlers in Axum must return something that implements IntoResponse. You've already seen that String and StatusCode each implement it individually. But if you return only a String, Axum always sends status 200 OK. If you return only a StatusCode, the response body is empty. Many API endpoints need to combine a non‑200 status with a description of what went wrong. The tuple (StatusCode, String) fills that gap.

The mechanism is simple: Axum provides tuple implementations of IntoResponse where the first element is a StatusCode and the rest is any type that also implements IntoResponse. In our case, String is the second element. When Axum sees the tuple, it takes the status code from the first part and the response body (and any headers) from the second part, then merges them into one complete HTTP response.

How Axum Converts the Tuple to a Response

Behind the scenes, the tuple goes through a chain of trait implementations:

  1. String implements IntoResponse → produces a Response with body "Nothing here" and status 200.
  2. StatusCode is handled by Axum's dedicated tuple implementations, which take a leading StatusCode and apply it to the response built from the rest of the tuple. It does not implement IntoResponseParts itself, which is why it can only appear first, never in the middle of a tuple.
  3. The final response now has the custom status and the original body.

This ordering is important: the String first creates a response with a default status, and then the StatusCode from the tuple overrides that status. If you ever wonder why the status in the tuple takes precedence, that's why.

Order in the Tuple Matters:

The tuple must always be (StatusCode, String) in that order. String goes second, never first. If you write (String, StatusCode), the compiler will complain because there is no IntoResponse implementation for that ordering.

Building the String Dynamically

Rarely will you hardcode the exact message. More often you'll want to include data from the request path, query parameters, or a database lookup. Since the second element of the tuple is a String, you can use format! or any other string-building method.

Here is a handler that reads a username from the URL and returns a personalized 404 message when the user is not found.

use axum::{extract::Path, http::StatusCode};
async fn get_user(Path(username): Path<String>) -> (StatusCode, String) {
    // Pretend we looked in a database and found no user
    let message = format!("User '{}' was not found", username);
    (StatusCode::NOT_FOUND, message)
}

When a client requests /users/alice, the response will be 404 with body User 'alice' was not found. The format! macro builds a new String at runtime, so the message is dynamic and meaningful.

You can also use any other method that returns a String. For example, a search handler that takes the search term from the URL path and reports the matches it found:

use axum::{extract::Path, http::StatusCode};
async fn search(Path(term): Path<String>) -> (StatusCode, String) {
    let results = ["axum guide", "axum examples", "axum reference"];
    let matches: Vec<&str> = results
        .iter()
        .filter(|item| item.contains(term.as_str()))
        .copied()
        .collect();
    if matches.is_empty() {
        (StatusCode::NOT_FOUND, format!("No results for '{}'", term))
    } else {
        (StatusCode::OK, format!("Results for '{}': {}", term, matches.join(", ")))
    }
}

The Path(term) part reads the search term from the URL, so a request to /search/guide gives term the value "guide". The handler filters a small list of titles for ones containing that term, then builds the message with format!. A request with no matches returns 404 with a clear message, while a request with matches returns 200 and the list joined with commas.

Multiple Status Codes from One Handler

A handler can return different status codes depending on the situation. The tuple makes this straightforward because you just return different StatusCode constants.

Consider a simple in‑memory key‑value store. The handler checks if a key exists and returns 200 with the value, or 404 with an error message.

use axum::{extract::Path, http::StatusCode};
use std::collections::HashMap;
async fn get_value(
    Path(key): Path<String>,
) -> (StatusCode, String) {
    // In a real app this map would be shared state
    let store: HashMap<String, String> = [
        ("name".to_string(), "Axum".to_string()),
        ("language".to_string(), "Rust".to_string()),
    ].into_iter().collect();
    match store.get(&key) {
        Some(value) => (StatusCode::OK, value.clone()),
        None => (StatusCode::NOT_FOUND, format!("Key '{}' not found", key)),
    }
}

The return type of the function is still (StatusCode, String). Both arms of the match produce exactly that type, so everything compiles. When the key is found, the client gets 200 and the value as plain text. When it is missing, the client gets 404 and a helpful message.

Variations: Using &'static str Instead of String

Sometimes you want to return a static message that never changes. String works, but it requires an allocation (a tiny performance cost). If your message is known at compile time, you can use a &'static str instead of String. The tuple type would be (StatusCode, &'static str). Axum supports this because &'static str also implements IntoResponse.

async fn permanent_redirect_notice() -> (StatusCode, &'static str) {
    (StatusCode::MOVED_PERMANENTLY, "This resource has moved")
}

However, this page is specifically about (StatusCode, String). The String version is more flexible because it can be built at runtime. If your message is always the same, &'static str is perfectly fine and a little cheaper. You can choose whichever fits your use case; Axum accepts both.

Don't Mix Up String and &'static str:

The tuple (StatusCode, String) and (StatusCode, &'static str) are different types. If your function's signature says (StatusCode, String) but you try to return a &str literal, you'll get a compile error unless you call .to_string() on it. Keep the types consistent.

Returning 201 Created with a Location Message

A common pattern in REST APIs is to return 201 Created after successfully creating a resource, along with a message telling the client where to find it. This is another perfect use for the tuple.

use axum::http::StatusCode;
async fn create_item() -> (StatusCode, String) {
    let new_id = 123; // pretend we inserted into a database
    (
        StatusCode::CREATED,
        format!("Item created with id {}", new_id),
    )
}

In a real API you might also include a Location header, but that would require more advanced tuple combinations. For this page, the tuple gives you the status and body, which is often enough for a simple acknowledgement.

Handling Errors with Result and the Tuple

Handlers can return a Result where the error type is (StatusCode, String). This lets you use the ? operator inside the handler and have errors automatically converted to a proper HTTP response.

use axum::{extract::Path, http::StatusCode};
async fn divide(Path((a, b)): Path<(i32, i32)>) -> Result<(StatusCode, String), (StatusCode, String)> {
    if b == 0 {
        return Err((StatusCode::BAD_REQUEST, "Division by zero".to_string()));
    }
    Ok((StatusCode::OK, format!("Result: {}", a / b)))
}

Here the success type and the error type are both (StatusCode, String). If the divisor is zero, the handler returns Err with a 400 status and a clear message. Axum will convert that Err into a response exactly as if you had returned it directly. This keeps error handling consistent.

Common Mistakes and How to Fix Them

Forgetting the Parentheses

A tuple is a pair of values wrapped in parentheses. If you write return StatusCode::NOT_FOUND, "Not found".to_string(); without parentheses, Rust will interpret this as returning two separate values from a function that expects one return type. The compiler error will be confusing for beginners. Always wrap the two values in parentheses:

// Wrong
async fn wrong() -> (StatusCode, String) {
    StatusCode::NOT_FOUND, "Not found".to_string() // error: expected `(StatusCode, String)`, found `StatusCode`
}
// Correct
async fn correct() -> (StatusCode, String) {
    (StatusCode::NOT_FOUND, "Not found".to_string())
}

Swapping the Tuple Elements

The order is fixed: status code first, body second. If you write ("Not found".to_string(), StatusCode::NOT_FOUND), the compiler will tell you that String doesn't implement IntoResponseParts. The status code must always come first.

Assuming the Body Is Always Non‑Empty

You can return an empty String as the body. That is valid and results in a response with Content-Length: 0 and no body. Some clients may handle an empty body differently, so be aware that if you intend to send a message, make sure it actually contains something meaningful.

async fn empty_message() -> (StatusCode, String) {
    (StatusCode::OK, String::new())
}

Check for Empty Messages:

Returning an empty String is legal, but it can confuse API consumers who expect a human‑readable error description. If you're building an API that other developers will call, always provide a non‑empty message for error statuses.

Full Working Example with a Router

Here is a complete main.rs that puts everything together. It defines three routes, each returning a (StatusCode, String) tuple with different behaviors. Run this and test with curl or a browser to see the responses.

use axum::{routing::get, Router, http::StatusCode, extract::Path};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/user/{name}", get(get_user))
        .route("/divide/{a}/{b}", get(divide));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> (StatusCode, String) {
    (StatusCode::OK, "Welcome to the demo".to_string())
}
async fn get_user(Path(name): Path<String>) -> (StatusCode, String) {
    if name == "admin" {
        (StatusCode::OK, format!("Hello, {}", name))
    } else {
        (StatusCode::NOT_FOUND, format!("User '{}' not found", name))
    }
}
async fn divide(Path((a, b)): Path<(i32, i32)>) -> (StatusCode, String) {
    if b == 0 {
        (StatusCode::BAD_REQUEST, "Cannot divide by zero".to_string())
    } else {
        (StatusCode::OK, format!("{} / {} = {}", a, b, a / b))
    }
}

Test each route:

  • curl -i http://127.0.0.1:3000/ → 200 OK with body Welcome to the demo
  • curl -i http://127.0.0.1:3000/user/admin → 200 OK with body Hello, admin
  • curl -i http://127.0.0.1:3000/user/bob → 404 Not Found with body User 'bob' not found
  • curl -i http://127.0.0.1:3000/divide/10/0 → 400 Bad Request with body Cannot divide by zero

Every route has exactly the same return type, but the actual status and body vary depending on logic. That uniformity makes the code easy to read and maintain.

Why Not Use impl IntoResponse?

You may have seen handlers with the return type impl IntoResponse. That hides a long tuple type behind a short signature, but it still stands for exactly one concrete type: you cannot return a StatusCode in one branch and a (StatusCode, String) in another, because impl Trait requires a single concrete type. For a handler that always returns a status + message, the explicit (StatusCode, String) return type is clearer and gives the compiler more information.

If you need more flexibility, you can always call .into_response() at the end of each branch to convert everything to a common Response type. But for this page's topic, sticking with the concrete tuple is simpler and works well.

Summary

The (StatusCode, String) tuple is the idiomatic way to return both an HTTP status code and a plain text message from an Axum handler. It combines two pieces that each implement IntoResponse into a single response, with the status code overriding the default 200 from the body.

The key insight is that this tuple is just a convenience. Underneath, Axum first builds a response from the String and then applies the StatusCode to it. That's why the order is fixed and why the status always takes effect. Once you understand that, you can confidently use it for 200 OK with a message, 404 with a description, 400 for validation errors, or any other combination of status and text.

If you need to attach additional headers, you can move to larger tuple combinations like (StatusCode, HeaderMap, String). For now, (StatusCode, String) covers the vast majority of simple text‑based responses you'll write in a beginner Axum application.