GET /health route

Learn how to build a GET /health route in Axum, what the handler returns, which status codes it uses, and how to test it with curl and with an in-process test

A GET /health route is a route that answers a GET request to the path /health with a short statement about the server's condition. The handler behind it returns a JSON object with a status field, and the HTTP status code carries the verdict: 200 when the server is able to work, 503 when it is not. Everything about the route, its method, its path, its response shape, and its speed, is chosen so that a machine can call it every few seconds and trust the answer.

Where This Fits

The previous idea explained what a health check is for and what it should and should not report. This page turns that idea into code: the exact handler, the exact route registration, the exact JSON body, and the exact status codes. Nothing here is new in concept. It is the same route, built properly, with the response shape a caller can parse.

Think of the difference between knowing a letter should be polite and actually writing one. The earlier page is the knowledge. This page is the letter: the greeting, the sentences, and the signature, in the right order, ready to send.

The Smallest Working Version

The smallest version returns a JSON object with one field. Create a project with this Cargo.toml and this src/main.rs.

# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
serde_json = "=1.0.145"
tokio = { version = "=1.54.1", features = ["full"] }
// src/main.rs
use axum::{routing::get, Json, Router};
use serde_json::json;

async fn health() -> Json<serde_json::Value> {
    Json(json!({"status": "ok"}))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello!" }))
        .route("/health", get(health));
    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();
}

Run it and call the route:

cargo run
curl http://127.0.0.1:3000/health
{"status":"ok"}

The response is a JSON object, which is text shaped like {"status": "ok"}. The curl output shows the body only. The status code is not shown unless curl is asked for it, and it is 200, which curl does not print by default. That is the whole route: one path, one method, one small JSON answer.

Working Setup:

If curl prints {"status":"ok"}, the route works. If it prints ok without the braces, the handler returns plain text instead of JSON, which is a different shape from the one on this page. If it prints a 404 page, the route is registered under a different path.

Understanding the Handler Line by Line

The handler is short, but every part of it does a job a beginner should understand. It is worth going slowly here, because this exact handler shape reappears in almost every real Axum project.

The return type

async fn health() -> Json<serde_json::Value> {

Json is Axum's wrapper that turns a Rust value into a JSON HTTP response. serde_json::Value is a value that can hold any JSON shape: an object, an array, a string, or a number. Together, Json<serde_json::Value> means "this handler returns some JSON, and the exact shape is decided inside the function". The handler takes no arguments, because a health check needs no input: no path parameter, no query string, no request body.

The body

Json(json!({"status": "ok"}))

The json! macro builds a JSON value from a literal written in Rust. {"status": "ok"} is a JSON object with one field, status, whose value is the string ok. Wrapping it in Json(...) tells Axum to serialise it, which means turning the Rust value into JSON text, and to set the Content-Type header to application/json. A caller that reads the header knows the body is JSON before it parses a single byte.

The serde_json crate must be listed in Cargo.toml for this to compile. Axum's Json type comes from Axum itself, but the json! macro and the Value type come from serde_json, and the project needs both crates. Forgetting the serde_json dependency is the most common compile error on this page, and the compiler reports it as an unresolved import, which is its way of saying the crate is not in the project.

Checking the Status Code with curl

The body is only half the answer. The status code is the other half, and curl hides it by default. The -i flag asks curl to print the response headers as well as the body, which shows the status line at the top.

curl -i http://127.0.0.1:3000/health
HTTP/1.1 200 OK
content-type: application/json
content-length: 15
date: Sat, 14 Nov 2026 12:00:00 GMT

{"status":"ok"}

The first line is the status line: the HTTP version, the code 200, and the words OK. The content-type line confirms the body is JSON. The content-length line says the body is 15 bytes long, which is the length of {"status":"ok"}. A caller reads the first line, sees 200, and knows the server is healthy without parsing anything else.

The -w flag prints just the code, which is useful in a script that checks health in a loop:

curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:3000/health
200

The -s flag silences curl's progress output, -o /dev/null throws the body away, and -w "%{http_code}" prints only the status code. A monitoring script that runs this line every few seconds and compares the output to 200 has built itself a health prober in one line.

Returning 503 When the Server Cannot Work

A health route that always returns 200 is an aliveness check: it reports that the process is running. A route that also checks a dependency returns 503 when that dependency is down. The handler below returns a tuple of a status code and a JSON body, which is how Axum lets a handler choose its status code instead of always sending 200.

// src/main.rs
use axum::{http::StatusCode, routing::get, Json, Router};
use serde_json::json;

async fn health() -> (StatusCode, Json<serde_json::Value>) {
    let database_up = check_database().await;
    if database_up {
        (StatusCode::OK, Json(json!({"status": "ok"})))
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"status": "error", "database": "unreachable"})),
        )
    }
}

async fn check_database() -> bool {
    true
}

The return type is a tuple, two values in one set of parentheses. The first is the status code, the second is the JSON body. Axum turns a tuple of a status code and a responder into a response with that status code and that body. When the database is up, the answer is 200 with {"status": "ok"}. When it is down, the answer is 503 with {"status": "error", "database": "unreachable"}. The error body names the problem in one word, unreachable, and reveals nothing else: no address, no password, no error text from the driver.

The check_database function here is a stand-in that always returns true. In a real project it would run a cheap query against the pool, with a short timeout, and return false if the query fails or times out. That real version belongs to the page about database checks in health routes, and this page keeps the stand-in so the shape of the handler stays clear.

Keep the Error Body Small:

The 503 body names the failing dependency and nothing more. A body that includes the database error text can leak the database address, the username, or the shape of the query, and all of that ends up in the caller's logs. One field naming the problem is enough for an operator to start investigating.

Adding the Uptime to the Response

A useful addition to the health body is the server's uptime, how long it has been running. It costs nothing to compute, and it tells an operator at a glance whether the server just restarted. The start time is stored in shared state when the server starts, and the handler reads it on each probe.

// src/main.rs
use axum::{extract::State, routing::get, Json, Router};
use serde_json::json;
use std::sync::Arc;
use std::time::Instant;

struct AppState {
    started_at: Instant,
}

async fn health(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
    Json(json!({
        "status": "ok",
        "uptime_seconds": state.started_at.elapsed().as_secs(),
    }))
}

#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        started_at: Instant::now(),
    });
    let app = Router::new()
        .route("/health", get(health))
        .with_state(state);
    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();
}

Instant::now() captures the moment the server starts, and elapsed() measures how long has passed since then. The state is wrapped in Arc, which is Rust's shared-ownership pointer, so the same state can be handed to the router and shared with every request. The handler extracts it with State, reads the elapsed time, and puts the number of seconds into the JSON. A probe after a minute returns something like {"status":"ok","uptime_seconds":63}, and a probe after a restart returns a small number again, which is how an operator spots that the server restarted without looking at the logs.

Why GET and Not POST

The route uses GET because a health check asks a question and changes nothing. In HTTP, GET is the method for reading, and POST is the method for changing something. A probe that used POST would be a strange request: it would ask the server to do something, and the server would have to decide what that something is. A GET request has no body, needs no input, and can be retried safely, which is exactly what a probe does every few seconds.

Using GET also means the route can be checked from a browser. A developer who types http://127.0.0.1:3000/health into a browser sees the JSON answer directly, with no tool needed. That convenience matters during development, when the fastest way to check the server is the browser already open on the screen.

Where the Route Is Registered

The health route is registered in the same router as the other routes, with the same .route call. It is not registered on a separate router or a separate port. The registration order does not matter: Axum matches the request path against every registered route, and /health matches exactly one of them. The route must be registered outside any authentication layer, so probes without a token still get an answer. In a project where most routes sit behind auth, the health route is registered on the outer router and the protected routes are nested inside, so the layer applies to them and not to the health check.

// src/lib.rs
use axum::{routing::get, Router};

pub fn app() -> Router {
    Router::new()
        .route("/", get(home))
        .route("/health", get(health))
}

async fn home() -> &'static str {
    "Welcome!"
}

async fn health() -> Json<serde_json::Value> {
    Json(json!({"status": "ok"}))
}

The health function is private to the module, because only the app function uses it. The app function is public, because main calls it. That matches the shape used across the project: handlers stay private, and the function that builds the router is the public one.

The Response Flow

The sequence below shows what happens between a probe arriving and the answer leaving.

Caller sends GET /health
        |
        v
Router matches the path /health and the method GET
        |
        v
health handler runs, builds the JSON value
        |
        v
Json wrapper serialises the value and sets content-type
        |
        v
Server sends 200 and {"status":"ok"}
        |
        v
Caller reads the status code first, the body second

Nothing in that flow touches a database, reads a file, or calls another service, unless the handler is the readiness version with a dependency check. The plain version is pure: a request in, a fixed answer out, in well under a millisecond.

Testing the GET /health Route

A test sends a GET request through the router without starting a server, and checks both the status code and the body. The body check parses the JSON and reads the status field, which proves the shape is the one the caller expects.

// tests/health_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn health_returns_200_with_ok_status() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(value["status"], "ok");
}

#[tokio::test]
async fn health_rejects_post() {
    let response = app()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
}

The test needs tower and serde_json as dev-dependencies:

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
serde_json = "=1.0.145"

The first test checks the happy path: status 200 and a body whose status field is ok. The second test checks that a POST to the same path is rejected with 405, which is the status code that means the method is not allowed for this route. That second test matters because it proves the route is a GET-only route, and a caller that accidentally probes with POST will get a clear rejection instead of a misleading answer.

The Test Needs the Real app Function:

Both tests call the same app() function that main calls, so they test the router the server actually serves. A test that builds its own router with a copy of the health route would pass even if the real router forgot to register the route. Always test the real app().

Common Beginner Mistakes

Returning plain text when the caller expects JSON

// Wrong - the body is ok, but the content-type is text, not JSON
async fn health() -> &'static str {
    "ok"
}

A plain-text answer is fine when the caller is a person reading curl output. It is wrong when the caller parses JSON, because a JSON parser handed the text ok fails: it is not valid JSON. The fix is the Json wrapper from the smallest version, which sets the content type and the body shape together. Decide the shape once, JSON or text, and keep it the same forever, because callers are written against the shape they first saw.

Registering the route with the wrong method

// Wrong - a GET probe to this route gets 405
let app = Router::new().route("/health", post(health));

A route registered with post only answers POST requests. A GET probe gets 405 Method Not Allowed, which the caller reads as unhealthy, and the server is pulled out of rotation. The fix is get(health), matching the method the probes actually use.

Forgetting serde_json in Cargo.toml

// Wrong - this fails to compile with an unresolved import
use serde_json::json;

The compiler error names serde_json as an unknown crate, which means the dependency is missing from Cargo.toml, not that the code is wrong. The fix is the serde_json = "=1.0.145" line in the smallest version's Cargo.toml. Axum does not re-export serde_json, so the project must depend on it directly.

A 404 on /health Means the Route Is Missing, Not the Server:

When a probe gets 404, the server is running fine and the route is not registered. Check the .route("/health", ...) line first: a typo in the path, a missing registration, or a route registered on a nested router under a different prefix are the usual causes. Do not restart the server or change the port before checking the registration.

Adding a slow check without a timeout

A readiness handler that awaits a database query with no timeout can hang for as long as the database takes to answer, and a hung database makes every probe hang with it. The caller times out, records a failure, and may restart a server that was only waiting on its database. The fix is a timeout around the check that is shorter than the probe timeout, so the route answers 503 quickly instead of hanging.

Final Complete Example

Here is everything from this page in one program: the library with the app function, the JSON health handler with a 503 branch, the main entry point, and the test that checks both the status and the body.

// src/lib.rs
use axum::{http::StatusCode, routing::get, Json, Router};
use serde_json::json;

pub fn app() -> Router {
    Router::new()
        .route("/", get(home))
        .route("/health", get(health))
}

async fn home() -> &'static str {
    "Welcome!"
}

async fn health() -> (StatusCode, Json<serde_json::Value>) {
    // Stand-in for a real check, which runs one cheap query with a short timeout.
    let database_up = true;
    if database_up {
        (StatusCode::OK, Json(json!({"status": "ok"})))
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"status": "error", "database": "unreachable"})),
        )
    }
}
// src/main.rs
use axum_project::app;

#[tokio::main]
async fn main() {
    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();
}
// tests/health_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn health_returns_200_with_ok_status() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(value["status"], "ok");
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
serde_json = "=1.0.145"
tokio = { version = "=1.54.1", features = ["full"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
serde_json = "=1.0.145"

Run it and probe it with the status code showing:

cargo run
curl -i http://127.0.0.1:3000/health
HTTP/1.1 200 OK
content-type: application/json
content-length: 15

{"status":"ok"}

Run the test:

cargo test

The response is small, fast, and machine-readable, which is everything a health route needs to be.

Summary

The most important insight is that the status code is the answer and the body is the detail. A caller that only reads the code can run a whole fleet of servers, because 200 means go and 503 means stop, and no parsing is needed. The body exists for the operator who wants to know why, and it should stay small enough to read at a glance. A health route that gets that split right, code for machines, body for people, does its job with fifteen bytes and a millisecond of work.

That split is also a decision framework for every variation on this page. Adding a field to the body is cheap, because bodies are for people. Changing the status code rules is expensive, because codes are for machines, and every caller has already been taught what 200 and 503 mean. Keep the code rules fixed and let the body grow slowly, and the route will stay compatible with every system that probes it, from a one-line curl loop to a deployment platform.