
Axum Docs
Build web APIs and services in Rust with Axum: routing, handlers, extractors, middleware, state, databases, auth, WebSockets, and deployment.
Axum is a Tokio-based web framework for Rust. You write ordinary async functions as handlers, extract request data with typed extractors, and compose middleware with Tower. It stays close to the Rust async ecosystem instead of inventing a separate abstraction layer.
Prerequisites:
These docs assume you can write basic Rust and use Cargo. If you are new to Rust, start with the Rust docs first, then come back here.
Here's the path through the docs:
- Introduction to Axum: HTTP basics, why Axum, and how it fits with Tokio and Hyper.
- Environment setup: Rust toolchain, editors, and helpful crates.
- Creating an Axum project: Cargo project, dependencies, and your first server.
- Project structure: how to organize routes, handlers, and modules as the app grows.
- Routing:
Router, method routers, path params, nest, merge, and fallbacks. - Handlers: async handlers, extractor arguments, and return types.
- Responses:
IntoResponse, JSON, status codes, and redirects. - Extractors:
Path,Query,Json, headers, and custom extractors. - Application state:
State,with_state, and shared data patterns. - Middleware: Tower layers,
from_fn, logging, and auth gates. - Later chapters cover errors, databases, authentication, WebSockets, SSE, uploads, testing, observability, configuration, and deployment.
Introduction To Axum
- Clientserver Model
- Http Request Structure
- Http Response Structure
- Http Methods Get Post Put Patch Delete
- Urls Paths And Query Strings
- Headers And Contenttype
- Status Code Ranges 2Xx 3Xx 4Xx 5Xx
- Http Statelessness
- What A Web Framework Provides
- Why Rust For Backend Services
- Blocking Vs Nonblocking I O
- What An Async Runtime Is
- Tokio Runtime Role
- Hyper As Http Engine
- Tower Service And Layer Idea
- Axum Version Line And Stability Notes
- Axum As Http Routing Library
- Axum As Request Handling Library
- Ergonomic Modular Design
- Macrofree Routing Api
- Tokio Team Maintenance
- Hyper Compatibility
- Tower Service Integration
- Tonic Middleware Sharing
- Ordinary Rust Function Handlers
- Typedriven Extractors
- Compose Small Welltyped Pieces
- Typesafe Routing
- Compiletime Extractor Checks
- Tower Reusable Middleware
- Towerhttp Layer Ecosystem
- Minimal Boilerplate
- Explicit Dependency Surface
- Predictable Error Model
- Async I O Via Tokio
- Fit For Tokiobased Teams
- Fit For Rest Json Apis
- Fit For Microservices Backends
- Fit For Spa Backends
- Fit For Mobile App Backends
- Fit For Desktop App Backends
- Fit For Bff Layers
- Fit For Websocket Backends
- Fit For Realtime Backends
- Actixweb In The Landscape
- Rocket In The Landscape
- Warp In The Landscape
- Hyper In The Landscape
- Actixweb Vs Axum Tower Service Model
- Actixweb Vs Axum Layer Composition
- Actixweb Actor Model Contrast
- Actixweb Vs Axum Extractor Style
- Actixweb Vs Axum Learning Curve
- Actixweb Vs Axum Macro Usage
- Actixweb Vs Axum Middleware Compatibility
- Actixweb Vs Axum Ecosystem Maturity
- Rocket Vs Axum Attribute Macros
- Rocket Vs Axum Macrofree Routes
- Rocket Vs Axum Handler Signatures
- Warp Vs Axum Filter Combinators
- Warp Vs Axum Router And Handlers
- Hyper As Http Library Vs Axum
- Axum Built On Hyper
- Axum Serve
Environment Setup
- Linux Platform Support
- Macos Platform Support
- Windows 10 Platform Support
- Windows 11 Platform Support
- Rustup Installer
- Macos Install Command
- Linux Install Command
- Windows Install Considerations
- Default Toolchain
- Rustc Version
- Cargo Version
- Rustup Update
- Vs Code Install
- Rustanalyzer Extension
- Codelldb Extension
- Cargo Fmt
- Cargo Clippy
- Cargowatch
- Sqlxcli
- Api Testing Tools
- Dbeaver
- Postgresql Server Install
- Default Port 5432
- Local Superuser
- Docker Install
- Docker Daemon
- Container Basics
- Cargo Check
- Stable Vs Nightly Channels
- Jetbrains Rust Plugin
- Neovim Rustanalyzer Setup
- Httpie Client
- Postman Or Insomnia
- Postgres In Docker Container
Creating An Axum Project
- Cargo New Myaxumapp
- Binary Crate
- Cargo Toml
- Src Main Rs
- Working Directory Cd Myaxumapp
- Default Hello World Template
- Axum Crate
- Tokio Crate
- Tokio Full Feature
- Serde Crate
- Serde Derive Feature
- Serde Json Crate
- Tower Crate
- Feature Flags Overview
- Axum Macros Feature
- Axum Multipart Feature
- Axum Ws Feature
- Axum Json Feature
- Axum Query Feature
- Axum Form Feature
- Axum Router
- Axum Routing Get
- Tokio Main
- Router New In Hello World
- Route Method
- Handler Async Fn
- Plain String Response
- Tokio Tcplistener
- Bind Address 127 0 0 13000
- Axum Serve
- Complete File Listing
- Cargo Run
- Browser Get
- Curl Get
- Baseline Curl Template
- Tokio Main Macro Revisit
- Async Handlers Requirement
- Router New Revisit
- Route Registration
- Tcplistener Bind
- Serve Function
- Git Init For The Project
- Gitignore For Rust
- Axum Tokio Version Compatibility
- Stopping The Server With Ctrlc
- Compile Warnings Vs Errors
Project Structure
- Thin Main Rs
- Lib Rs Module
- Pub Fn App
- Router Return Type
- Main Calls App
- Unchanged Behavior
- Cargo Run Regression
- Routes Directory
- Handlers Directory
- Models Directory
- State Rs Placeholder
- Error Rs Placeholder
- Mod Declarations
- Pub Use Reexports
- Layerbased Split
- Featurebased Split
- Domain Folders
- Cargo Workspaces
- When To Split Into Services
Routing
- Router New
- Router Type Parameter
- Route Method
- Method Routers
- Routing Get
- Routing Post
- Routing Put
- Routing Patch
- Routing Delete
- Routing Any
- Methodrouter Chaining
- Static Route Paths
- Route Path Parameters
- Users Id Syntax
- Multiple Path Parameters
- Fallback Routes
- Matchedpath Extractor Name
- Originaluri Extractor Name
- Nest Method
- Nest Path Prefix
- Nestedpath
- Routes Mod Rs
- Merge Method
- Merge Vs Nest
- Merge Modular Route Files
- Brace Param Syntax
- Legacy Colon Param Syntax
- Migrating Colon Params To Brace Params
- Brace Catchall Syntax
- Catchall Wildcard Segment
- Wildcard With Static Prefix
- Wildcard Placement Rules
- Empty Wildcard Match Behavior
- Capturing Wildcard As Path String
- Custom 404 Fallback Handler
- Fallback On Nested Routers
- Route Precedence When Paths Overlap
- Methodfilter Custom Methods
- Api Versioning With Nest
Handlers
- Async Fn Handlers
- Extractor Arguments
- Fromrequest In Handlers
- Fromrequestparts In Handlers
- Intoresponse Return
- Handler Trait
- Zeroargument Handlers
- Multiargument Handlers
- Handlers Users Rs
- Get User Function
- Path Argument Preview In Get User
- Placeholder User Value
- Handler Module Export
- Sync Requirement On Handlers
- One Handler File Per Resource
- Crud Handler Naming Conventions
- Keeping Handlers Thin
- Impl Intoresponse Vs Concrete Type
Responses
- Intoresponse Trait
- Static Str
- String Response
- Statuscode
- Headermap Response
- Response Tuples
- Statuscode String
- Statuscode Headermap Body
- Json Wrapper
- Html Wrapper
- Builtin Response Types Redirect
- No Content Response
- Serde Serialize
- Json T
- Contenttype Application Json
- User Struct
- Models User Rs
- Json Field Naming
- Response Builder
- Custom Response Headers
- Redirect To
- Redirect Permanent
- Empty Unit Response
- Returning Result From Handlers
- Streaming Body Preview
Extractors
- Fromrequest
- Fromrequestparts
- Extractor Order Rules
- Bodyconsuming Extractors Last
- Optional Extractors
- Rejection Types
- Custom Extractors Preview
- Path Extractor
- Path Single Parameter
- Path Tuple Parameters
- Path Struct Parameters
- Typed Path U32
- Path Deserialization Errors
- Rawpathparams
- Query Extractor
- Query Feature Flag
- Serde Query Structs
- Optional Query Fields
- Query Pagination Page Field
- Query Pagination Limit Field
- Rawquery
- List Users Handler
- Json Extractor
- Serde Deserialize
- Serialize Deserialize Derive Pair
- Json Default Body Limit
- Defaultbodylimit Layer
- Json Deserialization Rejection
- Create User Handler
- Post Create User Route
- Form Extractor
- Form Feature Flag
- Application Xwwwformurlencoded
- Rawform
- Headermap Extractor
- Headername
- Headervalue
- Typedheader
- Axumextra Dependency
- Authorization Header
- Useragent Header
- Extension Extractor
- Extension Layer
- Extension Requestscoped Data
- Missing Extension Runtime Error
- Extractor Argument Order
- Update User Example Signature
- Put Update User Route
- Custom Fromrequestparts Impl
- Custom Fromrequest Impl
- Cannot Impl Fromrequest And Fromrequestparts
- Authuser Sketch
- Authorization Parsing
- Bytes Body Extractor
- String Body Extractor
- Request Extractor
- Uri Extractor
- Matchedpath Extractor
- Originaluri Extractor
- Option T Optional Extraction
- Result T Rejection In Handlers
- Custom Path Types With Fromstr
- Contenttype Header Reading
- Withrejection Wrapper
- Exact Path Tuple Length Checks
Application State
- State Extractor Overview
- Request Extensions
- Closure Captures
- Tasklocal Variables
- Sharing Patterns Arc
- Sharing Patterns Mutex
- Sharing Patterns Rwlock
- Tokio Mutex Vs Std Mutex
- Appstate Struct
- Clone Derive
- With State
- Router S Type Parameter
- State Extractor With Appstate
- Inmemory Store
- Arc Mutex Vec
- Fromref Trait
- Fromref Derive
- Macros Feature
- Substate Extraction
- Appconfig Placeholder Field
- Perrequest Vs Shared Data
- State Vs Extension Contrast
- Send Sync Static Bounds
- Atomicusize Counters
- Atomicbool Flags
- Updating State Safely In Handlers
Middleware
- Service Trait
- Layer Trait
- Crosscutting Concerns
- Axum Middleware Module
- Towerhttp Crate
- Corslayer
- Tracelayer
- Compressionlayer
- Timeoutlayer
- Requestbodylimitlayer
- Setsensitiveheaderslayer
- Propagateheaderlayer
- Servedir Name
- Towerhttp Layer Ordering
- Middleware From Fn
- From Fn With State
- From Extractor
- From Extractor With State
- Map Request
- Map Request With State
- Map Response
- Map Response With State
- Next Type
- Request Logging Middleware
- Auth Check Middleware Preview
- Layer Method
- Route Layer
- Global Middleware
- Perroute Middleware
- Middleware Ordering Rules
- Tower Servicebuilder
- Requestid Correlation Layer
- Setrequestheader Layer
- Ratelimitlayer Overview
- Manual Service Impl For Middleware
- Manual Layer Impl For Middleware
- Injecting Extension From Middleware
Error Handling
- Intoresponse For Errors
- Result Return Type
- Infallible Handlers
- Rejection Mapping
- Apperror Enum
- Notfound Variant
- Validationerror Variant
- Internalerror Variant
- Apperror Intoresponse Impl
- Status Code Mapping
- Json Error Body
- Thiserror Crate
- Thiserror Derive
- Default Rejection Behavior
- Path Extractor Rejection
- Json Extractor Rejection
- Query Extractor Rejection
- Custom Rejection Override
- From Impl For Apperror
- Handlerresult Type Alias
- Unauthorized Error Variant
- Forbidden Error Variant
- Consistent Rejection And Apperror Json Shape
- Field Presence Checks
- Range And Length Checks
- 422 Responses With Field Errors
- Validator Crate
- Validate Derive Feature
- Validate Field Attributes
- Calling Validate In Handlers
- Validatedjson Custom Extractor
Database Integration
- Sqlx Overview
- Seaorm Overview
- Diesel Overview
- Db Crate Async Support
- Compiletime Checked Queries
- Orm Mapping Comparison
- Sqlx Crate
- Postgres Feature
- Runtimetokio Feature
- Pgpool
- Pgpooloptions
- Database Url
- Connection Pool Size
- Query Macro
- Query As Macro
- Sqlx Migrations
- Sqlxcli
- Sqlx Migrate
- Seaorm Crate
- Seaorm Entities
- Seaorm Migrations
- Seaquery
- Select Builder
- Insert Builder
- Update Builder
- Delete Builder
- Connection Options
- Db Module Separation
- Crud Create Post
- Crud Read Get One
- Crud Read Get List
- Crud Update Put
- Crud Update Patch
- Crud Delete
- Users Table
- Database Error Variants
- Sqlx Query Macro In Handlers
- Insert With Returning
- Embedding Migrations With Sqlx Migrate Macro
- Pagination With Limit And Offset
- Unique Constraint To 409 Mapping
- Missing Row To 404 Mapping
Authentication
- Sessionbased Auth
- Tokenbased Auth
- Jwt Auth Approach
- Unopinionated Axum Stance
- Argon2 Password Hashing
- Password Hash Column
- Signup Handler
- Password Verify
- Jwt Login Handler
- Jwt Token Claims
- Jwt Encoding Key
- Jwt Decoding Key
- Authuser Extractor
- Jwt Bearer Token
- Jwt Protected Route
- Auth Middleware
- Route Layer Auth
- Adminonly Route
- Role Claim
- Cors Allowed Origin
- Cors Allowed Methods
- Cors Allowed Headers
- Cors Credentials
- Towersessions Crate
- Session Cookie On Login
- Session Extractor In Handlers
- Logout By Clearing Session
- Session Check Middleware
- Jsonwebtoken Crate
- Refresh Token Flow
- Avoid User Enumeration In Auth Errors
- 401 Vs 403 Status Choice
- Requirerole Extractor
- Bcrypt As Password Alternative
Websockets
- Ws Feature Flag
- Websocketupgrade
- Websocket
- Websocket Message Types
- Websocket Text Messages
- Websocket Binary Messages
- Websocket Ping Pong
- Websocket Close Frame
- Websocket Echo Server
- Websocket Concurrent Connections
- Websocket Broadcast Channel
- Auth Headers On Upgrade
- Http Upgrade Handshake
- Websocket Vs Plain Http
- Splitting Sender And Receiver
- Client Disconnect Cleanup
- Ping Pong Keepalive Timer
- Utf8Bytes And Bytes Message Payloads
- Explicit Close Frames
Testing
- Cfg Test
- Pure Function Unit Tests
- Validation Helpers
- Tower Serviceext
- Tower Oneshot
- Test Request Builder
- Response Status Assertions
- Json Body Assertions
- Test File Layout
- Test Database Setup
- Sqlx Test
- Docker Postgres For Tests
- Createthenfetch Flow
- Transaction Rollback Strategy
- Tokio Test Attribute
- Seeding Fixture Data
- Authenticated Request In Tests
- Protected Route 401 Assertion
- Websocket Endpoint Test Client
- Sse Stream Response Test
- Mocking External Http Services
Building And Deployment
- Cargo Build Release
- Release Target Directory
- Release Binary Size
- Tokio Feature Trimming
- Dockerfile
- Multistage Build
- Docker Runtime Image
- Docker Build
- Docker Run
- Environment Variables At Runtime
- Graceful Shutdown
- Shutdown Signal
- Health Check Route
- Get Health Route
- Pool Size Tuning
- Https Termination
- Nginx Reverse Proxy
- Process Manager For Axum
- Platform Deploy Targets Overview
- Dockercompose With Postgres
- Draining Inflight Connections
- Database Connectivity In Health Check
- Liveness Vs Readiness
- Deploying To Fly Io
- Deploying To Render
- Deploying To Shuttle
- Custom Domain And Https
- Openapi With Utoipa
- Swagger Ui For Interactive Docs
- Inmemory Response Caching
- Redis As External Cache
- Perclient Rate Limiting
- Profiling With Flamegraph
- Benchmarking With Wrk Or Oha
- Tuning Tokio Worker Threads
- Serving Grpc With Tonic Beside Axum
- Graphql With Asyncgraphql