@axum-development

Build, structure, and test Rust HTTP services with Axum and Tower. Handle extractor ordering, typed AppState sub-states, IntoResponse errors, middleware layer order, and portless oneshot tests.

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

  1. 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 implement FromRequest (consuming the body).
  2. 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.
  3. Define a domain AppError enum that implements IntoResponse. 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.
  4. 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_blocking rather 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 with tower::ServiceExt::oneshot in #[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 using FromRef sub-state, a typed AppError response, 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::oneshot tests 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.