Rust HTTP Server with Axum

Build a type-safe HTTP server in Rust using Axum with extractors, JSON responses, error handling, and state sharing. Includes route definitions, middleware.

RustData Fetching

Code

snippet
use axum::{
  extract::State,
  http::StatusCode,
  response::Json,
  routing::get,
  Router,
};
use serde_json::{json, Value};
use std::sync::Arc;

struct AppState {
  db: String,
}

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

async fn get_data(State(state): State<Arc<AppState>>) -> Result<Json<Value>, StatusCode> {
  Ok(Json(json!({"db": state.db, "data": []})))
}

#[tokio::main]
async fn main() {
  let state = Arc::new(AppState { db: "postgres".into() });
  let app = Router::new()
    .route("/health", get(health))
    .route("/api/data", get(get_data))
    .with_state(state);
  let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
  axum::serve(listener, app).await.unwrap();
}

What the code does

Rust HTTP Server with Axum reduces to the functions health, get_data and main.

Fallible operations return Result, forcing the caller to handle both arms explicitly.

Caveats

  • Plan for an install step: axum:: and serde_json:: are a real dependency, resolved by the package manager.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

The main signature reads fn health() -> &'static str

Statements that matter

async fn get_data(State(state): State<Arc<AppState>>) -> Result<Json<Value>, StatusCode> {
  Ok(Json(json!({"db": state.db, "data": []})))
}
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();

Interactive Tools for This Topic

FAQ

What is the error handling style?
Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
What does this need from the package registry?
These are real dependencies: `axum::` and `serde_json::`. Without them the snippet will not load.