Returning Status Codes Directly in Axum

Learn how to return HTTP status codes like 200 OK and 404 Not Found directly from Axum handlers, how status codes work with the IntoResponse trait, and how to build dynamic status code logic step by step.

When a web browser asks your server for a page, the server always sends back two things: a body (the actual content, like HTML or JSON) and a status code. The status code is a three-digit number that tells the browser whether the request succeeded, failed, or needs something else to happen.

If you have ever seen a "404 Not Found" page, you have seen an HTTP status code in action. The number 404 is the status code. The words "Not Found" are a human-readable label attached to that number.

Axum lets you return a StatusCode directly from a handler. This page is entirely about that one feature: what StatusCode is, why you would return it on its own, how it behaves when you do, and how to use it for realistic situations.

The Simplest Possible Status Code Handler

Before we discuss anything else, here is the smallest complete Axum program that returns a status code. Create a new Axum project, put this in src/main.rs, and run it.

// src/main.rs
use axum::{
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> StatusCode {
    StatusCode::OK
}

The handler home returns StatusCode::OK, which is the number 200. The words "OK" are part of the constant name so that the code is easy to read; the actual value is just the integer 200.

When you run this program and open http://127.0.0.1:3000 in a browser, the page will be completely blank. That is expected. We returned only a status code, not any text or HTML. The browser sees the status code 200, understands it as "the request worked," and shows an empty page because no body was provided.

You can verify the status code from a terminal with curl:

curl -i http://127.0.0.1:3000

The -i flag tells curl to include the response headers. The first line of the output will look like this:

HTTP/1.1 200 OK

That line contains the status code we returned.

What StatusCode Is in Axum

StatusCode is not something Axum invented. It comes from the http crate, which Axum re-exports. You can import it from axum::http::StatusCode as we did above.

A StatusCode value wraps a 16-bit unsigned integer. The number must be between 100 and 999. Most status codes you will encounter fall into five ranges, and each range means something specific.

  • 100-199: informational responses; the server is not done yet but is telling the client something about the process
  • 200-299: success; the request worked
  • 300-399: redirection; the browser needs to go somewhere else
  • 400-499: client error; the browser asked for something invalid or unauthorized
  • 500-599: server error; something went wrong on the server

Because StatusCode is a wrapper around a number, you can create custom status codes if you ever need one that is not in Axum's list of named constants:

use axum::http::StatusCode;
async fn custom_status() -> StatusCode {
    StatusCode::from_u16(299).unwrap()
}

from_u16 returns a Result, because StatusCode validates that the number is in the 100-999 range. Passing 99 or 1000 would produce an error.

Common StatusCode Constants

Axum exposes 62 named constants on StatusCode in the http crate version Axum 0.8 uses. You do not need to memorize them. The ones you will use most often are:

ConstantNumberMeaning
StatusCode::OK200The request succeeded
StatusCode::CREATED201A new resource was created
StatusCode::ACCEPTED202The request was received but processing is not complete
StatusCode::NO_CONTENT204Success, but no body is being returned
StatusCode::BAD_REQUEST400The client sent invalid input
StatusCode::UNAUTHORIZED401The client must authenticate
StatusCode::FORBIDDEN403The client is authenticated but lacks permission
StatusCode::NOT_FOUND404The requested resource does not exist
StatusCode::METHOD_NOT_ALLOWED405The HTTP method is not supported for this route
StatusCode::INTERNAL_SERVER_ERROR500Something unexpected failed on the server
StatusCode::SERVICE_UNAVAILABLE503The server is temporarily unable to handle requests

Each constant name describes what the status code means. When you type StatusCode::NOT_FOUND, you are writing code that is much easier to understand than a bare 404.

Here is a single router with several routes, each returning a different status code:

// src/main.rs
use axum::{
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/created", get(created))
        .route("/missing", get(missing))
        .route("/broken", get(broken));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> StatusCode {
    StatusCode::OK
}
async fn created() -> StatusCode {
    StatusCode::CREATED
}
async fn missing() -> StatusCode {
    StatusCode::NOT_FOUND
}
async fn broken() -> StatusCode {
    StatusCode::INTERNAL_SERVER_ERROR
}

Each route returns a different status code. A browser visiting /missing would see the browser's built-in "404 page not found" display, because the browser knows how to render that status code. Visiting /broken would show a generic "500 Internal Server Error" page.

Browsers and Status Codes:

Browsers often replace your response body with their own built-in error page for certain status codes, especially 404 and 500. This does not mean your code is wrong. If you want to see the actual status code without any browser interference, use a tool like curl -i or an HTTP client such as Postman or Bruno.

How IntoResponse Converts StatusCode

Axum handlers must return types that implement the IntoResponse trait. A type that implements this trait can be converted into a full HTTP response.

StatusCode implements IntoResponse on its own. When you return StatusCode::NOT_FOUND, Axum automatically calls the trait's conversion logic and produces an HTTP response with:

  • The status code set to 404
  • An empty body
  • No custom headers beyond the defaults Axum and the underlying HTTP server add

The result looks like this as a raw HTTP response:

HTTP/1.1 404 Not Found
content-length: 0
date: Tue, 16 Sep 2025 10:22:45 GMT

The body is empty. The content-length header says the body has zero bytes. There is no content-type header, because there is no content to describe.

This behavior matters when you are building an API. A client that expects JSON in every response might be surprised when a StatusCode-only handler sends back an empty body. The status code itself is the entire message. If you need both a status code and a body, use a tuple like (StatusCode, String), which pairs the status with a text body. For now, the key point is that returning only a StatusCode always produces an empty body.

Why Return a StatusCode Alone

At first, an empty response might seem useless. But there are many cases where the status code is the only thing the client cares about.

Creating a Resource with 201 Created

When an API creates a new record, the client often already knows what data it sent. The client does not need the server to echo that data back. It only needs to know that the creation succeeded. A 201 Created status code tells them exactly that.

Deleting with 204 No Content

Axum has a separate type called NoContent for returning 204, but StatusCode::NO_CONTENT works the same way when you need only the status. A delete operation commonly returns 204 with no body, because the deleted resource no longer exists and there is nothing to send back.

Checking Health with 200 OK

Load balancers and monitoring services often ping an endpoint like /health every few seconds. They do not care about a response body. They only need to know whether the server is alive. Returning StatusCode::OK is the fastest and simplest answer.

Here is a realistic health check route:

// src/main.rs
use axum::{
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/health", get(health_check));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn health_check() -> StatusCode {
    StatusCode::OK
}

A monitoring tool can send a GET request to /health every few seconds. If the response status code is 200, the server is considered healthy. If the server is down, there is no response at all, and the monitor reports an outage.

Status-only responses are perfectly valid:

In HTTP, a response does not need a body. Many production APIs return status codes with empty bodies for create, delete, and health operations. If your client is surprised by an empty body, the problem is usually that the client assumed a body would always exist, not that the server is wrong.

Building a Router That Chooses Status Codes Dynamically

So far, every handler has returned a hardcoded status code. Real applications choose status codes based on what actually happened during the handler. This is where StatusCode becomes powerful.

We will build a small API with a list of users stored in memory. The handler receives a user ID, looks it up in the list, and returns either 200 OK or 404 Not Found.

// src/main.rs
use axum::{
    extract::Path,
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn get_user(Path(id): Path<u32>) -> StatusCode {
    // A simple in-memory list of user IDs.
    let existing_ids = [1, 2, 3, 42, 99];
    if existing_ids.contains(&id) {
        StatusCode::OK
    } else {
        StatusCode::NOT_FOUND
    }
}

The path parameter {id} captures whatever number appears in the URL. The Path extractor converts that segment into a u32. If the number is in our array, we return 200 OK. If not, we return 404 Not Found.

Test it with curl:

$ curl -i http://127.0.0.1:3000/users/3
HTTP/1.1 200 OK
$ curl -i http://127.0.0.1:3000/users/100
HTTP/1.1 404 Not Found

This example shows how status codes become dynamic. The handler inspects input, makes a decision, and returns the status code that describes the outcome.

A Subtle Point About This Example

Returning 404 with an empty body is correct for a simple lookup API. But many clients, especially web frontends, expect a JSON error message explaining what went wrong. If you are building a public API, you will eventually want to return (StatusCode::NOT_FOUND, "User not found") so the body contains details. The status code alone is best when the client only needs a success/failure signal, not a detailed explanation.

Returning Different Status Codes from One Handler

The previous example returned two different status codes from one handler. That works because StatusCode is a concrete type. The function signature says -> StatusCode, and every branch returns the same type. No matter which branch runs, the handler always produces a value of exactly the same type.

This is an important detail in Rust. Axum handlers can return many different things, but within a single handler, the return type must stay consistent. If you try to return StatusCode in one branch and a string in another, the compiler will reject the code:

// This does NOT compile
async fn broken_handler(flag: bool) -> StatusCode {
    if flag {
        StatusCode::OK
    } else {
        "hello"  // Error: expected StatusCode, found &str
    }
}

One branch produces StatusCode and the other produces &str. These are different types, so the function signature is invalid.

When you need to return completely different response types from one handler, you have two options. The first is to call .into_response() on each value and make the return type axum::response::Response. The second is to use a Result type. For this page, the rule to remember is: when returning StatusCode, every code path must return a StatusCode.

Using StatusCode with the IntoResponse Trait

StatusCode implements IntoResponse, but you rarely call .into_response() on it yourself in a handler. Axum calls that conversion for you automatically. However, understanding that the conversion exists helps you understand what is happening behind the scenes.

Here is what the automatic conversion looks like if we wrote it manually:

use axum::{
    http::StatusCode,
    response::IntoResponse,
};
async fn handler() -> axum::response::Response {
    StatusCode::NOT_FOUND.into_response()
}

The return type is now axum::response::Response, which is a full HTTP response object. The into_response() method converts the status code into that object.

In most handlers, you should simply return StatusCode and let Axum do the conversion. But this manual conversion is useful when you have a handler that might return different response types in different branches. For example:

// src/main.rs
use axum::{
    extract::Path,
    routing::get,
    Router,
    http::StatusCode,
    response::{IntoResponse, Response},
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/resource/{id}", get(get_resource));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn get_resource(Path(id): Path<u32>) -> Response {
    let is_valid_id = id % 2 == 0;
    if is_valid_id {
        // Return a status code with no body.
        StatusCode::OK.into_response()
    } else {
        // Return a status code with a text body.
        (StatusCode::BAD_REQUEST, "Only even IDs are allowed").into_response()
    }
}

This handler returns Response as its type. In one branch, it returns a bare StatusCode. In the other branch, it returns a tuple of (StatusCode, String). Both are converted to Response by calling .into_response(). Without the manual conversion, these two branches would have incompatible types and the code would not compile.

This is an advanced pattern. Beginners should stick to simple StatusCode return types until the need for mixed responses actually appears in their own project. When it does appear, remember that .into_response() is the tool that unifies different response types.

StatusCode and the 204 No Content Case

StatusCode::NO_CONTENT deserves a special mention because it has a specific rule in the HTTP standard: a 204 response must not include a body.

When you return StatusCode::NO_CONTENT from a handler, Axum correctly sends an empty body. The raw response looks like this:

HTTP/1.1 204 No Content

There is no content-length header, because there is no body to measure. Some HTTP clients treat a missing content-length header as unusual, but for 204 responses it is correct behavior.

Here is a handler that uses 204 for a delete operation:

// src/main.rs
use axum::{
    routing::delete,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{id}", delete(delete_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn delete_user() -> StatusCode {
    // In a real app, you would delete the user from a database here.
    StatusCode::NO_CONTENT
}

The route uses the HTTP DELETE method. The handler returns 204 No Content, which is the standard response for a successful delete with nothing to return. Clients should interpret 204 as "the operation succeeded, and there is no body to read."

204 responses must not have a body:

The HTTP standard forbids sending a body with a 204 status code. If you try to attach a body to a 204 response manually, some HTTP clients will reject it or behave unpredictably. When returning StatusCode::NO_CONTENT alone, Axum handles this correctly for you.

Working with the StatusCode Type Directly

StatusCode is not just a set of constants. It is a full type with methods you can call. Knowing a few of these methods makes you more comfortable when reading Axum code in real projects.

Checking the numeric value

use axum::http::StatusCode;
fn print_status_details() {
    let status = StatusCode::NOT_FOUND;
    println!("Status as a number: {}", status.as_u16());
    println!("Is success: {}", status.is_success());
    println!("Is client error: {}", status.is_client_error());
    println!("Is server error: {}", status.is_server_error());
}

as_u16() returns the raw integer. The other methods return booleans based on the numeric range. is_success() checks if the code is in the 200-299 range. is_client_error() checks 400-499. is_server_error() checks 500-599.

These methods appear frequently in middleware and error handling code. If you ever need to inspect a response's status code after it has been created, these methods are what you use.

Creating from a number

We saw from_u16 earlier. It is the safe way to create a status code from user input or a database value:

use axum::http::StatusCode;
async fn handler() -> Result<StatusCode, StatusCode> {
    let code_from_database: u16 = 203;
    match StatusCode::from_u16(code_from_database) {
        Ok(status) => Ok(status),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

from_u16 validates the range. If the number is outside 100-999, it returns an error. The handler above maps that error to a 500 Internal Server Error, which is a reasonable fallback.

Getting the canonical reason phrase

The HTTP standard defines a short text phrase for each status code. For 200, the phrase is "OK". For 404, it is "Not Found". You can retrieve this phrase with canonical_reason():

use axum::http::StatusCode;
fn print_reason() {
    let status = StatusCode::NOT_FOUND;
    println!("Reason phrase: {:?}", status.canonical_reason());
}

Output:

Reason phrase: Some("Not Found")

The method returns an Option<&str>, because some custom status codes do not have an official reason phrase defined by the standard. For those, the method returns None.

StatusCode and the 404 Fallback Handler

Axum has a feature called a fallback handler, which runs when no route matches the incoming request. This is a common place to return StatusCode::NOT_FOUND.

// src/main.rs
use axum::{
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .fallback(not_found);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> StatusCode {
    StatusCode::OK
}
async fn not_found() -> StatusCode {
    StatusCode::NOT_FOUND
}

When a request comes in for a route that does not exist, Axum invokes not_found. That handler returns 404 Not Found. This is one of the simplest real-world uses of StatusCode: you are telling the client "I looked, and this route does not exist."

The fallback approach is useful because it gives you a single place to control what happens when a request has no matching route. You can return a bare status code, or a tuple with a body that says "Page not found."

StatusCode in Nested Routers

Larger Axum applications split routes across multiple routers and nest them together. StatusCode works exactly the same inside nested routers.

// src/main.rs
use axum::{
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let users_router = Router::new()
        .route("/", get(list_users));
    let app = Router::new()
        .route("/", get(home))
        .nest("/users", users_router);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> StatusCode {
    StatusCode::OK
}
async fn list_users() -> StatusCode {
    StatusCode::OK
}

The nested router handles requests to /users. The handler list_users returns StatusCode::OK. Nothing about StatusCode changes when it is inside a nested router. The same conversion logic applies.

This matters because it shows that StatusCode is a portable, reusable response type. You can define handlers that return StatusCode and use them anywhere in your router tree without adjustments.

Combining StatusCode with Other Response Parts

So far, we have only returned StatusCode alone. But Axum's design allows you to combine a StatusCode with other response parts, such as a body, headers, or extensions. The important concept for this page is that StatusCode can appear as the first element of a tuple.

A tuple like (StatusCode, String) means "this status code, plus this body." A tuple like (StatusCode, HeaderMap, String) means "this status code, plus these headers, plus this body." The StatusCode element always comes first in the standard tuple forms.

Here is a small preview that shows a status code paired with a body:

// src/main.rs
use axum::{
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> (StatusCode, &'static str) {
    (StatusCode::CREATED, "User created")
}

When you send a request to this route, curl -i shows:

HTTP/1.1 201 Created
content-type: text/plain; charset=utf-8
content-length: 12
User created

The status code is 201, and the body is the text "User created". Axum automatically sets the content-type header to text/plain.

But this page is about returning StatusCode alone. The tuple form is mentioned only so you understand that the solo form is a deliberate choice. When you return only a status code, you are saying: "No body, no custom headers, just the status."

Common Misconceptions About StatusCode

Some ideas about StatusCode trip up beginners repeatedly. We will name them explicitly here.

Misconception 1: Returning 200 OK is always correct

Beginners sometimes write handlers that always return StatusCode::OK, even when something went wrong. A handler that fails to find a resource but still returns 200 is lying to the client. The client sees "success" and assumes the resource exists, when in fact it does not.

The rule is simple: return the status code that describes what actually happened. If a lookup fails, return 404. If input is invalid, return 400. If something unexpected breaks, return 500.

Misconception 2: The status code is enough to debug a failed request

A 500 Internal Server Error tells you something went wrong on the server. It does not tell you what went wrong. If your server logs are empty, you will have a hard time diagnosing the issue.

In production, pair status codes with proper logging. Log the error that caused a 500 before returning the status code to the client. The client sees 500, but your logs contain the actual stack trace or error message.

Misconception 3: StatusCode and body are always sent separately

HTTP sends the status code and body in the same response. The status code comes first in the status line, then headers, then the body. Returning only a StatusCode just means the body has zero bytes. It is not a separate communication channel.

This matters because some clients read only the body and ignore the status code. Those clients will see an empty string and think the server returned nothing useful. If you are building an API for such clients, you may need to include a body that mirrors the status code, like {"status": 404}.

Status code and body must agree:

Never return a 200 OK status code with an error message body that says "not found" or "failed". The status code and the body must tell the same story. If the body says something failed, the status code should be in the 400 or 500 range. Mixing success status with error content confuses clients and breaks caching logic.

A Complete Worked Example: User Lookup API

Let's put everything together in one complete example. This API accepts a user ID in the path, validates it, and returns an appropriate status code.

// src/main.rs
use axum::{
    extract::Path,
    routing::get,
    Router,
    http::StatusCode,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/users/{id}", get(get_user))
        .fallback(not_found);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> StatusCode {
    StatusCode::OK
}
async fn get_user(Path(id): Path<u32>) -> StatusCode {
    // Simulating a database query for specific user IDs.
    let known_users = [10, 20, 30, 40, 50];
    if known_users.contains(&id) {
        StatusCode::OK
    } else {
        StatusCode::NOT_FOUND
    }
}
async fn not_found() -> StatusCode {
    StatusCode::NOT_FOUND
}

Walk through what happens for four different requests.

Request 1: GET /

The router matches the / route. The home handler runs and returns 200 OK. The response is an empty body with status 200.

Request 2: GET /users/20

The router matches the /users/{id} route. The Path extractor parses 20 as a u32. The handler checks known_users and finds 20 in the array. It returns 200 OK.

Request 3: GET /users/25

The router matches /users/{id}. The extractor parses 25. The handler checks known_users and does not find 25. It returns 404 Not Found.

Request 4: GET /anything-else

No route matches. The fallback runs and returns 404 Not Found.

This example demonstrates the full workflow: routing, extraction, decision-making, and status code selection. The handler does not need a database or external service; the logic is self-contained and easy to test.

Testing Handlers That Return StatusCode

Handlers that return StatusCode are easy to test in Rust. Axum provides a oneshot helper for calling a handler directly without running a full server.

First, add tower to your Cargo.toml as a dev dependency:

# Cargo.toml
[dev-dependencies]
tower = "0.5"

Then create a test module:

// src/main.rs
use axum::{
    routing::get,
    Router,
    http::StatusCode,
    body::Body,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> StatusCode {
    StatusCode::OK
}
#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::Request;
    use tower::ServiceExt;
    #[tokio::test]
    async fn home_returns_200() {
        let app = Router::new().route("/", get(home));
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }
}

The test builds a router, sends a fake request using tower::ServiceExt::oneshot, and checks that the response status is 200. This is a complete, repeatable test that does not require spinning up a real network listener.

Run it with:

cargo test

The test should pass. If you change the handler to return a different status code, the test will fail, giving you immediate feedback.

Testing status codes catches regressions early:

A test that asserts a specific status code is one of the most valuable tests you can write for an API. If a future code change accidentally makes a successful handler return 500 or a not-found handler return 200, the test fails immediately and tells you exactly where the bug is.

Summary

StatusCode is one of the smallest and most direct response types in Axum. Returning it from a handler produces an empty-bodied response whose only meaningful content is the three-digit HTTP status number.

The value of StatusCode comes from what it communicates. A 200 tells a client "this worked." A 404 tells a client "that does not exist." A 500 tells a client "something broke on the server." Understanding when to return each one - and pairing the right status code with the right situation - is a fundamental skill for building HTTP APIs.

This page covered status-code-only responses. The natural next step is combining StatusCode with a body, which is what the (StatusCode, String) tuple is for. Once you understand status codes alone, adding a body on top feels like a small extension rather than a new concept.