Axum and Rust Web Services Tutorial
Learn Axum and Rust Web Services step by step: 38 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Axum? Rust Web Services Overview Meet Axum, the Rust web framework built on Tokio, Tower and Hyper: what it does, how a request flows through it, and when to choose it for an API or web service.
- Setting Up an Axum Project with Cargo Create a new Rust crate for Axum, choose dependencies and features, write the Tokio entry point, read configuration from the environment and run your first request.
- HTTP Basics for Axum Developers Review the HTTP concepts every Axum handler uses: methods, status codes, headers, bodies and content types, with Rust types from the http crate and runnable models.
- Your First Axum Server: Routes, JSON and Shutdown Build a small Axum server step by step: a text route, a JSON route, a custom port, clean Ctrl+C shutdown, and a runnable loopback model of the request cycle.
- Axum Project Layout, Logging and Configuration Organise an Axum codebase into modules, add structured logging with tracing and RUST_LOG filters, and keep configuration in one typed struct that fails fast.
Routers and Handlers
- Axum Routing Basics: Router, route and Methods Learn how Axum routes requests: Router::new and route, method routers like get and post, chaining several methods on one path, any, and how 405 responses are produced.
- Axum Handler Functions and the Handler Trait Understand what makes an async function an Axum handler: extractor arguments, the body-consuming last argument, IntoResponse return types, closures, and how to read handler errors.
- Axum Path Parameters, Captures and Wildcards Capture URL segments in Axum 0.8 with {id} and {*rest}, extract them as numbers, tuples or structs with Path, understand match priority, and handle parse failures.
- Nesting and Merging Axum Routers Split an Axum app into modules with Router::nest, nest_service and merge: prefixes, stripped paths, OriginalUri, conflicts and the 0.8 root-nesting rule.
- Axum Fallbacks, 404 and 405 Responses Customize what Axum answers when no route matches: Router::fallback, method_not_allowed_fallback, the Allow header, JSON 404s, fallback_service and nested fallbacks.
Extractors and Responses
- Path and Query Extractors in Axum Read query strings in Axum with Query<T>: optional filters, defaults with serde, pagination limits, repeated keys, percent-decoding, and combining Path with Query.
- JSON and Form Bodies in Axum Accept request bodies in Axum with Json<T>, Form<T>, String and Bytes: content-type rules, 400, 415 and 422 rejections, body size limits and validation patterns.
- Custom Extractors and Rejections in Axum Write your own Axum extractors with FromRequestParts and FromRequest, return JSON rejections, wrap Json for validation, and understand extractor order and the macros.
- Headers, Cookies and Uploads in Axum Read request headers with HeaderMap and TypedHeader, manage cookies with CookieJar, set response headers, and receive multipart file uploads in Axum with limits.
- Responses and IntoResponse in Axum Build Axum responses with the IntoResponse trait: strings, status tuples, headers, Json, Html, Redirect, Result, Response::builder, streaming and server-sent events.
State and Middleware
- Shared State in Axum: State, Arc and Mutex Share data between Axum handlers with State, with_state and FromRef: Arc<Mutex>, RwLock, atomics, database pools, substates, and the Extension alternative.
- Middleware in Axum with from_fn Write Axum middleware as async functions with from_fn: run code before and after handlers, return early, share state, apply layers to groups, and learn the layer order.
- Axum Middleware with tower-http: CORS, Trace, Compression Use ready-made tower-http layers in Axum: TraceLayer logging, CorsLayer and preflight requests, compression, timeouts, body limits, request ids and static files.
- Request Extensions and Request IDs in Axum Pass per-request data from middleware to handlers with Axum extensions, build a CurrentUser pattern, add request ids for log correlation, and use ConnectInfo and MatchedPath.
Async, Tokio and Tower
- Async, Await and Futures Understand what async fn, await and Future really are in Rust, why Axum handlers are futures, and build a tiny executor with the standard library to see polling and wakers work.
- The Tokio Runtime and Tasks Learn how #[tokio::main], tokio::spawn, JoinHandle, spawn_blocking and channels work behind an Axum server, with runnable standard-library stand-ins for worker pools and message passing.
- Tower Services and Layers Learn the Tower Service and Layer traits that power Axum middleware, how ServiceBuilder orders layers, and how tower-http adds tracing, CORS, compression and timeouts, with a runnable stand-in.
- Graceful Shutdown and Timeouts Shut an Axum server down cleanly with with_graceful_shutdown, handle Ctrl+C and SIGTERM, drain in-flight requests, and add per-request timeouts, with runnable stand-ins for the shutdown and deadline logic.
Databases with SQLx
- Setting Up SQLx and Connection Pools Add SQLx to an Axum app, create a PgPool with PgPoolOptions, share it through State, size the pool sensibly and understand acquire timeouts, with a runnable pool stand-in.
- Queries and Row Mapping with SQLx Run SQL from Axum handlers with sqlx::query, query_as and the query! macros, bind parameters safely, map rows with FromRow, and choose fetch_one, fetch_optional or fetch_all, with a runnable mapping stand-in.
- CRUD Endpoints with SQLx Build create, read, update and delete endpoints in Axum with SQLx: RETURNING clauses, status codes, partial updates, pagination and a runnable repository stand-in showing the handler logic.
- Migrations and Transactions in SQLx Version your schema with sqlx migrate, run migrations at startup, and keep multi-step writes consistent with SQLx transactions, commit and rollback, with runnable stand-ins for both mechanisms.
Authentication and Errors
- Error Handling with IntoResponse Design an AppError enum for Axum, implement IntoResponse and From conversions so the ? operator works in handlers, return consistent JSON errors and avoid leaking internals, with runnable stand-ins.
- Password Hashing and Registration Store passwords safely in an Axum API with Argon2id: salts, PHC strings, spawn_blocking, login verification, constant-time compare and user-enumeration pitfalls, plus runnable teaching stand-ins.
- JWT Authentication in Axum Issue and verify JSON Web Tokens in Axum with the jsonwebtoken crate: claims, expiry, secrets, Bearer headers, refresh tokens and when sessions are better, with a runnable signed-token stand-in.
- Authentication Middleware and Authorization Protect Axum routes with a custom FromRequestParts extractor or from_fn middleware, add role checks and per-resource ownership rules, and understand 401 versus 403, with runnable stand-ins.
Testing and Deployment
- Testing Handlers with oneshot Test Axum routers without opening a socket. Build requests, call the Router with oneshot, read the response body, and structure fast unit and route tests, with runnable stand-ins.
- Integration Tests with a Test Database Test Axum and SQLx code against a real database with sqlx::test, isolate every test, load fixtures, and swap repositories for fakes, with runnable Rust stand-ins.
- Configuration, Docker and Deployment Ship an Axum service. Read configuration from the environment, build a small multi-stage Docker image, add health checks and run migrations safely, with runnable Rust stand-ins.
- Observability and Production Hardening Make an Axum service production ready with request IDs, structured tracing, metrics, body limits, CORS and rate limiting, with runnable Rust stand-ins for the key algorithms.
Projects and Practice
- Project: A URL Shortener Design and build a URL shortener service with Axum and SQLx. Plan the routes and schema, generate short codes, validate URLs, redirect and count clicks, with runnable Rust stand-ins.
- Project: A Notes API with Authentication Build a multi-user notes API with Axum, SQLx and JWT authentication. Plan routes and schema, enforce ownership, paginate lists and map errors, with runnable Rust stand-ins.
- Axum Practice and Review Review the Axum course with a production checklist, common mistakes, and hands-on exercises such as idempotency keys and a retry policy, with runnable Rust stand-ins and solutions.