Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 38 ยท Getting Started

Your First Axum Server: Routes, JSON and Shutdown

Build a small Axum server step by step: a text route, a JSON route, a custom port, clean Ctrl+C shutdown, and a runnable loopback model of the request cycle.

You now know the pieces. This lesson puts them together into a first real server that you can run, call with curl, and stop cleanly. We start with the smallest possible program and grow it: add a JSON endpoint, log requests, and handle Ctrl+C so in-flight requests finish before the process exits.

The Axum code is read-only in this page. Beside it you will run a model of the same server built from std::net and threads, so you can watch the whole request cycle happen.

Step 1: the smallest server

Rust
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, Axum!" }));

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

The route handler here is an async closure that returns a &'static str. Axum turns it into a 200 OK response with content-type: text/plain; charset=utf-8. Named functions are clearer once handlers grow, so we switch to them next.

Step 2: a JSON endpoint

Rust
use axum::{routing::get, Json, Router};
use serde::Serialize;

#[derive(Serialize)]
struct Greeting {
    message: String,
    version: u32,
}

async fn root() -> &'static str {
    "Hello, Axum!"
}

async fn greeting() -> Json<Greeting> {
    Json(Greeting {
        message: "Hello from JSON".to_string(),
        version: 1,
    })
}

fn app() -> Router {
    Router::new()
        .route("/", get(root))
        .route("/api/greeting", get(greeting))
}

Json<T> serialises T with serde_json and sets content-type: application/json. Notice that app() returns a Router instead of building it inside main. That small habit pays off in the testing chapter because tests can call app() without opening a port.

Try it:

Terminal
curl -s http://127.0.0.1:3000/api/greeting
# {"message":"Hello from JSON","version":1}

Step 3: shutting down gracefully

If you kill a server with Ctrl+C mid-request, the client sees a broken connection. Axum supports graceful shutdown: stop accepting new connections, let current requests finish, then exit. You give serve a future that completes when it is time to stop:

Rust
use tokio::signal;

async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c().await.expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install SIGTERM handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
}

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app())
        .with_graceful_shutdown(shutdown_signal())
        .await
        .unwrap();
}

tokio::select! waits for whichever signal arrives first. SIGTERM is what Docker, systemd and Kubernetes send when they stop your service, so handling it matters in production. We return to this in deployment.

A runnable model of the whole cycle

The Axum crate is not available here, so this model uses the standard library. It has a tiny route table (method and path to a function), a server thread that serves exactly three connections, and a client that calls two routes and one missing path. The shape is the same as Axum's: parse, route, produce a response, write it.

Rust Stand-in: a tiny router served over loopback TCP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Axum's Router replaces the HashMap, and Hyper replaces the manual reading and writing, but the outline is the same.

A model of graceful shutdown

Graceful shutdown means: after the stop signal, no new work starts, and work already running is allowed to finish. This model uses an atomic flag for the signal and worker threads that finish their current job before exiting.

Rust Stand-in: stop accepting work, finish what is running

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The in-flight request finishes; the later ones are refused. Axum's with_graceful_shutdown does this for connections: it stops the listener, waits for open requests, then returns from serve.

Common first-server problems

  • "Address already in use". Another process owns the port. Pick another one or stop the old process.
  • A handler that will not compile. The error mentions Handler is not implemented. Usually an argument is not an extractor, or the return type is not IntoResponse. See handler functions.
  • Nothing happens when you curl. Check the bound address and that the process is still running; with a container, bind to 0.0.0.0.
  • Panics inside a handler. Hyper catches them per connection, but fix them: return errors instead of unwrap(). See error handling.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why return the Router from a function like app() instead of building it inside main?

    A separate constructor lets tests call the router directly; main only binds the port and serves.
  2. 2. What does with_graceful_shutdown do?

    You pass a future (such as a Ctrl+C or SIGTERM listener); when it completes the server drains and exits.
  3. 3. Which signal do Docker and Kubernetes send to ask a service to stop?

    SIGTERM is the polite stop request, so a production server should shut down gracefully on it.
  4. 4. What content type does returning Json<T> set?

    Json<T> serialises with serde_json and sets content-type: application/json.

Summary

  • A first server is a Router, a bound TcpListener and axum::serve.
  • Return Json<T> for JSON; return &str for plain text.
  • Build the router in a function so tests can reuse it.
  • Pass a shutdown future to with_graceful_shutdown and handle both Ctrl+C and SIGTERM.

Next: Project Layout, Logging and Configuration