axum-web-framework

Complete guide for Axum web framework including routing, extractors, middleware, state management, error handling, and production deployment

By manutej · 583 installs

npx skills add manutej/luxor-claude-marketplace --skill axum-web-framework

Source repository · Upstream listing

Axum Web Framework A comprehensive skill for building production ready web applications and APIs using Axum, the ergonomic and modular Rust web framework built on Tokio and Tower. Master routing, extractors, middleware, state management, error handling, and deployment patterns. When to Use This Skill Use this skill when: Building REST APIs with Rust and async/await Creating high performance web services with type safety Developing microservices with Tokio ecosystem integration Implementing WebSocket servers or Server Sent Events (SSE) Building GraphQL APIs with Rust backend Creating middleware heavy applications requiring Tower integration Developing production ready web applications requiring robust error handling Building systems requiring fine grained control over HTTP request/response handling Implementing authentication, authorization, and security middleware Creating real time web applications with async Rust Developing APIs requiring request validation and transformation Building web services with complex routing and nested routers Implementing rate limiting, timeout, and backpressure handling Creating web applications requiring custom extractors and response types Core Concepts Axum Architecture Philosophy Axum is built on three fundamental pillars: 1. Tower Services : Everything in Axum is built on Tower's Service trait, providing composability and middleware integration 2. Type Safe Extractors : Request data extraction is compile time checked, eliminating runtime parsing errors 3. Minimal Boilerplate : Ergonomic APIs that reduce ceremony while maintaining explicitness The Router The Router is the central building block in Axum. It maps HTTP requests to handlers based on path and method. Key Properties: Routes are matched in the order they're defined Routers can be nested for modular organization Middleware can be applied at router, route, or method level Generic over state type for flexible state management Implements Tower's Service trait for composability Router Creation: Handlers Handlers are async functions that process requests and return responses. Axum supports multiple handler signatures through its powerful type system. Handler Requirements: Must be async functions Can extract data from requests using extractors Must return types implementing IntoResponse Can have up to 16 parameters (all must be extractors) Common Handler Patterns: Extractors Extractors are types that implement FromRequest or FromRequestParts , allowing type safe extraction of data from requests. Built in Extractors: 1. Path Extract path parameters 2. Query Extract query string parameters 3. Json Parse JSON request body 4. Form Parse form encoded request body 5. State Access shared application state 6. Extension Access request extensions 7. Headers Access request headers 8. Method Get HTTP method 9. Uri Get request URI 10. Request Get full request 11. Bytes Raw request body as bytes 12. String Request body as UTF 8 string 13. Multipart Handle multipart/form data Extractor Ordering: Extractors that consume the request body must come last Multiple body extractors in one handler will cause compilation errors State and other non body extractors can be in any order Responses Any type implementing IntoResponse can be returned from handlers. Axum provides many built in implementations. Built in Response Types: String , &'static str Text responses Json<T JSON responses Html<String HTML responses StatusCode Status only responses (StatusCode, T) Status with body (Parts, T) Custom headers with body Response Full control over response Result<T, E Error handling (where E: IntoResponse) State Management Axum uses the State extractor to share data across handlers. State must implement Clone and is typically wrapped in Arc for shared ownership. State Patterns: 1. Simple State: 2. Shared State with Arc: 3. Multiple State Types: Middleware Middleware in Axum comes from Tower and provides request/response transformation, logging, authentication, and more. Middleware Categories: 1. Tower Middleware From tower and tower http crates 2. Custom Middleware Using middleware::from fn 3. Service Middleware Implementing Tower's Service trait 4. Layer Pattern Using Tower's Layer for composability Middleware Application Order: Applied with .layer() executes bottom to top (wrapping previous layers) Applied with ServiceBuilder executes top to bottom (more intuitive) Middleware on Router::layer runs after routing Middleware around Router (using Layer::layer ) runs before routing Error Handling Axum's error handling is built on the IntoResponse trait, allowing custom error types to be converted to HTTP responses. Error Handling Strategies: 1. Result Types: 2. Custom Error Types: 3. HandleErrorLayer: Tower Integration Axum is built on Tower, enabling powerful middleware composition and service abstraction. Key Tower Concepts: 1. Service Trait Asynchronous request processing 2. Layer Trait Middleware factory pattern 3. ServiceBuilder Ergonomic middleware composition 4. Timeout Request timeout handling 5. RateLimit Request rate limiting 6. LoadShed Backpressure management 7. Buffer Request buffering Routing Basic Routing Routes map HTTP methods and paths to handlers: Path Parameters Extract dynamic segments from paths: Wildcard Routes Capture remaining path segments: Important: Nested routers strip matched prefixes, but wildcard routes retain the full URI. Nested Routers Organize routes into modules using router nesting: Nesting Behavior: Matched prefix is stripped from URI before passing to nested router Handlers in nested routers only see path relative to nest point Fallback handlers are inherited from parent if not defined in child Middleware can be applied before or after nesting Fallback Handlers Handle unmatched routes: Fallback Inheritance: Method Routing Handle multiple HTTP methods on the same route: Extractors Deep Dive Path Extractor Extract typed path parameters: Query Extractor Extract query string parameters: Json Extractor Parse JSON request bodies: JSON Error Handling: State Extractor Access shared application state: Extension Extractor Access request extensions (useful for middleware): Form Extractor Parse form encoded request bodies: Headers Extractor Access request headers: Custom Extractors Create custom extractors by implementing FromRequest or FromRequestParts : Middleware Applying Middleware Three Ways to Apply Middleware: 1. Router level Affects all routes 2. Route level Affects specific routes 3. Method level Affects specific methods on a route Middleware Execution Order With sequential .layer() calls (bottom to top): With ServiceBuilder (top to bottom): Common Tower Middleware TraceLayer HTTP request tracing: CompressionLayer Response compression: CorsLayer CORS handling: TimeoutLayer Request timeouts: HandleErrorLayer Convert middleware errors to HTTP responses: Custom Middleware with from fn Create custom middleware using async functions: Passing data from middleware to handler: Custom Tower Middleware Implement Tower's Service and Layer traits for full control: Middleware with State Access Create middleware that accesses application state: Middleware Before Routing Apply middleware before routing (e.g., for URI rewriting): State Management Basic State Simple state with cloneable types: Shared State with Arc Use Arc for shared ownership of expensive to clone types: Multiple State Types Use different state types for different router sections: Generic State in Functions Return routers with generic state for flexibility: State Transitions Chain routers with different state requirements: Error Handling Basic Error Handling with Result Use Result to handle errors in handlers: Custom Error Types Implement IntoResponse for custom errors: Extractor Rejection Handling Handle extractor rejections for better error messages: Custom Extractors with Error Handling Create extractors with custom rejection types: Middleware Error Handling Handle errors from fallible middleware: Fallible Services Route to services that can fail: Response Building JSON Responses Return JSON with type safety: HTML Responses Serve HTML content: Status Code Responses Return different status codes: Custom Headers Add custom headers to responses: Full Response Control Build complete responses: Streaming Responses Stream data to clients: File Downloads Serve files for download: Production Patterns Database Integration Integrate with database pools: Configuration Management Use environment variables and configuration: Structured Logging Implement comprehensive logging: Graceful Shutdown Implement graceful shutdown handling: Health Checks Implement health check endpoints: Rate Limiting Implement rate limiting: Request Validation Validate requests with custom extractors: Testing Unit Testing Handlers Test handlers in isolation: Integration Testing Test full application: Best Practices Handler Organization 1. Keep handlers thin Move business logic to service layer 2. Use extractors Let type system handle extraction 3. Return Result types Use custom error types 4. Instrument handlers Add tracing for observability State Management 1. Use Arc for expensive types Database pools, caches 2. Keep state minimal Only what's truly shared 3. Implement Clone Required for State extractor 4. Avoid mutation Use interior mutability (RwLock, Mutex) when needed Error Handling 1. Create custom error types Implement IntoResponse 2. Provide context Include helpful error messages 3. Log errors appropriately Use tracing 4. Return proper status codes Match HTTP semantics Middleware 1. Use ServiceBuilder More intuitive ordering 2. Apply at right level Router vs route vs method 3. Handle errors Use HandleErrorLayer for fallible middleware 4. Keep middleware focused Single responsibility Performance 1. Use connection pooling For databases and external services 2. Enable compression CompressionLayer for responses 3. Implement caching Reduce redundant operations 4. Use backpressure LoadShedLayer, RateLimitLayer 5. Optimize serialization Use efficient JSON libraries Security 1. Validate inputs Use custom extractors with validation 2. Implement authentication Use middleware for auth 3. Use HTTPS In production environments 4. Set security headers CORS, CSP, etc. 5. Rate limit Prevent abuse Common Patterns Repository Pattern Service Layer Pattern Versioned APIs Skill Version : 1.0.0 Last Updated : October 2025 Skill Category : Web Development, REST APIs, Rust, Async Programming Compatible With : Axum 0.7+, Tokio 1.0+, Tower 0.4+