Axum Cheat Sheet
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A single-page, colour-coded summary of web development with axum, written against axum 0.8.9, tokio 1.53 and tower-http
0.7.1 on Rust 1.99 (checked 2026-10-06) — the tokio, hyper, tower and axum stack with a request’s life, the Cargo.toml
and main.rs skeleton with axum::serve and graceful shutdown, routing with {param} and {*rest} captures, nest,
merge and fallbacks, the extractor table with the body-extractor-last rule and optional extractors, responses and an
AppError recipe, State, FromRef and Extension, middleware with from_fn and the layer-ordering rules, the
tower-http layers with body limits, timeouts and CORS, validation and utoipa snippets, sqlx pool, query, transaction and
migration one-liners, a sessions, passwords, JWT, OAuth2 and CSRF checklist, askama with htmx, WebSocket, SSE and
multipart skeletons, tracing, OpenTelemetry and metrics setup, testing with oneshot and axum-test, a deployment
checklist, and a strip of what changed since older tutorials — handy for quick memorization or as a
downloadable PDF desk reference.
For the full explanation, every option, and additional examples, see the dedicated pages:
Start here — Axum.
Foundations — Introduction & Architecture, Tower Service Model, Getting Started and Project Structure.
Routing, handlers, extractors and responses — Routing, Routing Composition, Handlers, Extractors, Custom Extractors, axum-extra, Responses, Error Handling and State & Dependency Injection.
Middleware and HTTP concerns — Writing Middleware, Applying Middleware & Ordering, tower-http Catalog, Request Limits & Timeouts, CORS & Compression and Rate Limiting & Load Shedding.
Building APIs — JSON REST APIs, Validation, OpenAPI with utoipa, Forms & Content Negotiation and GraphQL & gRPC.
Security — Sessions & Cookies, Password Authentication, JWT & Bearer Tokens, OAuth2 & OpenID Connect, Authorization, CSRF & Security Hardening and TLS & HTTPS.
Web UI and real-time — Server-side Templates, htmx, Static Files & SPAs, WebSockets, Server-Sent Events & Streaming, File Uploads and Full-stack with Leptos & Dioxus.
Operations — Background Jobs & Tasks, HTTP Clients & Proxies, Graceful Shutdown, Configuration, Logging & Tracing, OpenTelemetry & Distributed Tracing, Metrics & SLOs, Testing, Performance Tuning and Deployment.
Reference — Migration & Framework Comparison.
Worked example
A complete, runnable check of the routing and extractor rules above: a router with one typed path capture is called
in-process with tower::ServiceExt::oneshot, so no port is opened. It needs axum, tokio (with the macros and
rt-multi-thread features), serde_json, tower (with util) and http-body-util.
use axum::{
body::Body,
extract::Path,
http::Request,
routing::get,
Json, Router,
};
use http_body_util::BodyExt;
use serde_json::{json, Value};
use tower::ServiceExt;
async fn book(Path(id): Path<u32>) -> Json<Value> {
Json(json!({ "id": id, "title": "Rust in Action" }))
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/books/{id}", get(book));
for uri in ["/books/42", "/books/abc", "/missing"] {
let request = Request::get(uri).body(Body::empty()).unwrap();
let response = app.clone().oneshot(request).await.unwrap();
let status = response.status();
if status.is_success() {
let body = response.into_body().collect().await.unwrap().to_bytes();
println!("GET {uri} -> {status} {}", String::from_utf8_lossy(&body));
} else {
println!("GET {uri} -> {status}");
}
}
}
GET /books/42 -> 200 OK {"id":42,"title":"Rust in Action"}
GET /books/abc -> 400 Bad Request
GET /missing -> 404 Not Found
The typed Path<u32> rejects abc with 400 before the handler runs, and an unmatched path falls through to the
default 404 fallback.
References
The PDF summarizes the official documentation; each source is cited in full on the page listed above that covers it, and in the section bibliography.