Axum Web Framework
Complete guide for Axum web framework including routing, extractors, middleware, state management, error handling, and production deployment
- Skill ID
- manutej/luxor-claude-marketplace/axum-web-framework
- Publisher
- manutej
- Repository
- luxor-claude-marketplace
- Installs
- 0
- Files
- 3
- Synced
- Sep 23, 2026
Open any RiverX project, open the Skills panel in the chat, and search for this identifier. The files are fetched from the source repository at install time.
manutej/luxor-claude-marketplace/axum-web-frameworkInstalls these files- EXAMPLES.md
- README.md
- SKILL.md
What this skill tells the agent
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:
- Tower Services: Everything in Axum is built on Tower's
Servicetrait, providing composability and middleware integration - Type-Safe Extractors: Request data extraction is compile-time checked, eliminating runtime parsing errors
- 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
Servicetrait for composability
Router Creation:
use axum::{Router, routing::get};
let app = Router::new()
.route("/", get(handler))
.route("/users/:id", get(get_user))
.route("/posts", get(list_posts).post(create_post));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:
// Simple handler
async fn handler() -> &'static str {
"Hello, World!"
}
// Handler with path parameter
async fn get_user(Path(user_id): Path<u32>) -> String {
format!("User ID: {}", user_id)
}
// Handler with multiple extractors
async fn create_user(
State(state): State<AppState>,
Json(payload): Json<CreateUser>,
) -> Result<Json<User>, StatusCode> {
// Implementation
}Extractors
Extractors are types that implement FromRequest or FromRequestParts, allowing type-safe extraction of data from requests.
Built-in Extractors:
- Path - Extract path parameters
- Query - Extract query string parameters
- Json - Parse JSON request body
- Form - Parse form-encoded request body
- State - Access shared application state
- Extension - Access request extensions
- Headers - Access request headers
- Method - Get HTTP method
- Uri - Get request URI
- Request - Get full request
- Bytes - Raw request body as bytes
- String - Request body as UTF-8 string
- 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
Stateand 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 responsesJson<T>- JSON responsesHtml<String>- HTML responsesStatusCode- Status-only responses(StatusCode, T)- Status with body(Parts, T)- Custom headers with bodyResponse- Full control over responseResult<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:
- Simple State:
#[derive(Clone)]
struct AppState {
api_key: String,
}
let app = Router::new()
.route("/", get(handler))
.with_state(AppState {
api_key: "secret".to_string(),
});- Shared State with Arc:
#[derive(Clone)]
struct AppState {
db_pool: Arc<DatabasePool>,
cache: Arc<RwLock<Cache>>,
}- Multiple State Types:
// Define separate state types for different router sections
let api_router: Router<ApiState> = Router::new()
.route("/api/data", get(api_handler));
let app_router: Router<AppState> = Router::new()
.route("/app", get(app_handler));
// Combine with final state
let app = Router::new()
.nest("/", app_router.with_state(app_state))
.nest("/", api_router.with_state(api_state));Middleware
Middleware in Axum comes from Tower and provides request/response transformation, logging, authentication, and more.
Middleware Categories:
- Tower Middleware - From
towerandtower-httpcrates - Custom Middleware - Using
middleware::from_fn - Service Middleware - Implementing Tower's
Servicetrait - Layer Pattern - Using Tower's
Layerfor composability
Middleware Application Order:
- Applied with
.layer()executes bottom-to-top (wrapping previous layers) - Applied with
ServiceBuilderexecutes top-to-bottom (more intuitive) - Middleware on
Router::layerruns after routing - Middleware around
Router(usingLayer::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:
- Result Types:
async fn handler() -> Result<Json<Data>, StatusCode> {
// Returns 200 OK or error status code
}- Custom Error Types:
enum AppError {
Database(sqlx::Error),
NotFound,
Unauthorized,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
// Convert to HTTP response
}
}- HandleErrorLayer:
use axum::error_handling::HandleErrorLayer;
let app = Router::new()
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(handle_error))
.layer(TimeoutLayer::new(Duration::from_secs(30)))
);Tower Integration
Axum is built on Tower, enabling powerful middleware composition and service abstraction.
Key Tower Concepts:
- Service Trait - Asynchronous request processing
- Layer Trait - Middleware factory pattern
- ServiceBuilder - Ergonomic middleware composition
- Timeout - Request timeout handling
- RateLimit - Request rate limiting
- LoadShed - Backpressure management
- Buffer - Request buffering
Routing
Basic Routing
Routes map HTTP methods and paths to handlers:
use axum::{
Router,
routing::{get, post, put, delete, patch},
};
let app = Router::new()
.route("/", get(root))
.route("/users", get(list_users).post(create_user))
.route("/users/:id", get(get_user).put(update_user).delete(delete_user))
.route("/posts/:id/comments", get(get_comments).post(add_comment));Path Parameters
Extract dynamic segments from paths:
More from manutej
Use this skill in a project
Open any RiverX project, search the Skills panel for manutej/luxor-claude-marketplace/axum-web-framework, and install it in one click.
