Axum Development
When to Use
- Build or refactor HTTP routes, extractors, and typed error responses in a Rust Axum service.
- Wire shared application state (
State<T>,FromRef) and Tower middleware layers without subtle execution-order bugs. - Write fast, portless integration tests for Axum routers using
tower::ServiceExt::oneshot.
Prerequisites
Check the Axum major/minor version in Cargo.toml (Axum 0.8 uses /{id} path parameter syntax, replacing the /:id syntax from 0.7), Tokio runtime features, Tower/tower-http middleware versions, and Rust toolchain version. Inspect Router assembly, shared state types, custom error types, and existing tests before adding endpoints or middleware.
Structure routes, extractors, and error responses
- Order handler parameters carefully: extractors that read parts of the request (
State,Path,Query,HeaderMap) must come before body-consuming extractors (Json,Bytes,String,Form), because only the last extractor may implementFromRequest(consuming the body). - Keep handler dependencies narrow by implementing
axum::extract::FromRef<AppState>for sub-states (for example a database pool or limits config). Attach state with.with_state(state)once all stateful routes are merged. - Define a domain
AppErrorenum that implementsIntoResponse. Return structured JSON error codes and appropriate HTTP status codes for caller errors (4xx), and log internal errors server-side without leaking stack traces, SQL text, or credentials in 5xx responses. - For Axum 0.8+, use
{param}and{*wildcard}route capture syntax; verify migrated routes explicitly when upgrading from 0.7.
Reason about Tower middleware layering order
- In Axum,
.layer(L)wraps all previously registered routes. Layers added later wrap earlier ones from the outside in: a request enters the outermost (last-added).layer(...)first and exits it last. - Use
.route_layer(...)when middleware should run only on matched routes (so unmatched 404s skip authentication or route-specific metrics) and.layer(...)when middleware must wrap every response, including 404s and extractor rejections (such as request IDs, CORS, or tracing). - Keep middleware non-blocking and offload CPU-heavy or blocking I/O work with
tokio::task::spawn_blockingrather than stalling Tokio worker threads.
Test routers in-process and verify shutdown
- Extract router construction into a pure helper (
fn build_app(state: AppState) -> Router) and exercise routes withtower::ServiceExt::oneshotin#[tokio::test]without binding TCP sockets. Assert status codes, response headers set by middleware, valid JSON payloads, domain errors, and malformed input rejections. - In production entry points, wire
axum::serve(listener, app).with_graceful_shutdown(...)and verify cancellation/shutdown behavior separately in an authorized local run.
Example
Build an Axum 0.8
POST /items/{id}endpoint usingFromRefsub-state, a typedAppErrorresponse, and a request-ID middleware layer, then test valid, invalid, and malformed requests in-process.
Use the worked Axum handler and middleware test to verify extractor ordering, structured 422 errors, and middleware header injection across success and rejection paths.
Limitations
tower::ServiceExt::oneshottests the router and Tower layers in-process without exercising TLS termination, TCP socket binding, keep-alive timeouts, or OS signal graceful shutdown.- This skill focuses on Axum 0.8+ HTTP routing and Tower composition; WebSocket protocols, gRPC (
tonic), and database drivers (sqlx/diesel) require their own driver-specific checks.
Safety and Side Effects
Run tests in an isolated crate or checkout without opening public network listeners. Cargo builds may download crates on an uncached machine and execute crate build scripts or proc macros; inspect Cargo.toml and lockfiles before building unfamiliar workspaces. Never include secrets or production database URLs in test fixtures or error responses.
Related Skills and Documentation
- For Tokio tasks, channels, cancellation, and avoiding blocking async workers, see Rust Async Patterns.
- For Cargo workspace layout, linting, and Rust project scaffolding, see Rust Project Scaffolding.
- For general Rust idioms, ownership, and error design, see rust-pro.
- See Axum's official docs.rs reference, extractors guide, and middleware ordering documentation.