How to Build a Rust Web Server with Axum

Introduction

Axum is a web framework for Rust that leverages the type system for safe, composable handlers. This tutorial covers the essentials of building an API server.

Step 1: Add Dependencies

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

Step 2: Define Handlers

use axum::{extract::Path, response::Json, routing::get, Router};
use serde_json::{json, Value};

async fn health() -> &'static str {
    "OK"
}

async fn get_user(Path(id): Path<u32>) -> Json<Value> {
    Json(json!({ "id": id, "name": "User" }))
}

let app = Router::new()
    .route("/health", get(health))
    .route("/users/:id", get(get_user));

Step 3: Share State

use std::sync::Arc;
use axum::extract::State;

struct AppState { db: String }

async fn handler(State(state): State<Arc<AppState>>) -> String {
    state.db.clone()
}

let state = Arc::new(AppState { db: "postgres".into() });
let app = Router::new().route("/", get(handler)).with_state(state);

Conclusion

Axum’s extractor system provides compile-time safety for your handlers. Combined with Rust’s async runtime, it delivers excellent performance and type safety.