Axum — Ergonomic Rust Web Framework

You are an expert in Axum, the web framework built on top of Tokio and Tower by the Tokio team. You help developers build high-performance, type-safe APIs and web services using Axum's extractor-based handler system, middleware via Tower layers, WebSocket support, and compile-time route validation — achieving C-level performance with Rust's memory safety guarantees.

25 stars

Best use case

Axum — Ergonomic Rust Web Framework is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

You are an expert in Axum, the web framework built on top of Tokio and Tower by the Tokio team. You help developers build high-performance, type-safe APIs and web services using Axum's extractor-based handler system, middleware via Tower layers, WebSocket support, and compile-time route validation — achieving C-level performance with Rust's memory safety guarantees.

Teams using Axum — Ergonomic Rust Web Framework should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/axum/SKILL.md --create-dirs "https://raw.githubusercontent.com/ComeOnOliver/skillshub/main/skills/TerminalSkills/skills/axum/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/axum/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How Axum — Ergonomic Rust Web Framework Compares

Feature / AgentAxum — Ergonomic Rust Web FrameworkStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

You are an expert in Axum, the web framework built on top of Tokio and Tower by the Tokio team. You help developers build high-performance, type-safe APIs and web services using Axum's extractor-based handler system, middleware via Tower layers, WebSocket support, and compile-time route validation — achieving C-level performance with Rust's memory safety guarantees.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Axum — Ergonomic Rust Web Framework

You are an expert in Axum, the web framework built on top of Tokio and Tower by the Tokio team. You help developers build high-performance, type-safe APIs and web services using Axum's extractor-based handler system, middleware via Tower layers, WebSocket support, and compile-time route validation — achieving C-level performance with Rust's memory safety guarantees.

## Core Capabilities

### Application Setup

```rust
// src/main.rs — Axum API server
use axum::{
    Router, Json, Extension,
    extract::{Path, Query, State},
    http::StatusCode,
    routing::{get, post, put, delete},
    middleware,
};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use std::sync::Arc;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
struct AppState {
    db: PgPool,
    redis: redis::Client,
}

#[tokio::main]
async fn main() {
    tracing_subscriber::init();

    let db = PgPool::connect(&std::env::var("DATABASE_URL").unwrap())
        .await.unwrap();

    let state = AppState {
        db,
        redis: redis::Client::open("redis://127.0.0.1/").unwrap(),
    };

    let app = Router::new()
        .route("/users", get(list_users).post(create_user))
        .route("/users/{id}", get(get_user).put(update_user).delete(delete_user))
        .route("/health", get(|| async { "OK" }))
        .layer(CorsLayer::permissive())
        .layer(TraceLayer::new_for_http())
        .with_state(state);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

### Handlers and Extractors

```rust
// Extractors pull data from requests — type-safe at compile time

#[derive(Deserialize)]
struct CreateUserRequest {
    name: String,
    email: String,
}

#[derive(Serialize)]
struct UserResponse {
    id: i64,
    name: String,
    email: String,
    created_at: chrono::NaiveDateTime,
}

// State, Path, Query, Json are all extractors
async fn create_user(
    State(state): State<AppState>,        // Application state
    Json(payload): Json<CreateUserRequest>, // Request body
) -> Result<(StatusCode, Json<UserResponse>), AppError> {
    let user = sqlx::query_as!(
        UserResponse,
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *",
        payload.name,
        payload.email,
    )
    .fetch_one(&state.db)
    .await?;

    Ok((StatusCode::CREATED, Json(user)))
}

async fn get_user(
    State(state): State<AppState>,
    Path(id): Path<i64>,                  // URL path parameter
) -> Result<Json<UserResponse>, AppError> {
    let user = sqlx::query_as!(UserResponse, "SELECT * FROM users WHERE id = $1", id)
        .fetch_optional(&state.db)
        .await?
        .ok_or(AppError::NotFound)?;

    Ok(Json(user))
}

#[derive(Deserialize)]
struct ListParams {
    page: Option<u32>,
    per_page: Option<u32>,
}

async fn list_users(
    State(state): State<AppState>,
    Query(params): Query<ListParams>,     // Query string parameters
) -> Result<Json<Vec<UserResponse>>, AppError> {
    let page = params.page.unwrap_or(1);
    let per_page = params.per_page.unwrap_or(20).min(100);
    let offset = ((page - 1) * per_page) as i64;

    let users = sqlx::query_as!(
        UserResponse,
        "SELECT * FROM users ORDER BY id LIMIT $1 OFFSET $2",
        per_page as i64,
        offset,
    )
    .fetch_all(&state.db)
    .await?;

    Ok(Json(users))
}
```

### Error Handling

```rust
use axum::response::IntoResponse;

enum AppError {
    NotFound,
    Database(sqlx::Error),
    Unauthorized,
}

impl IntoResponse for AppError {
    fn into_response(self) -> axum::response::Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "Resource not found"),
            AppError::Database(e) => {
                tracing::error!("Database error: {e}");
                (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
            }
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized"),
        };
        (status, Json(serde_json::json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(e: sqlx::Error) -> Self { AppError::Database(e) }
}
```

### Middleware

```rust
use axum::middleware::Next;
use axum::http::Request;

async fn auth_middleware(
    State(state): State<AppState>,
    mut req: Request<axum::body::Body>,
    next: Next,
) -> Result<impl IntoResponse, AppError> {
    let token = req.headers()
        .get("Authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .ok_or(AppError::Unauthorized)?;

    let user = validate_token(&state.db, token).await?;
    req.extensions_mut().insert(user);
    Ok(next.run(req).await)
}

// Apply to specific routes
let protected = Router::new()
    .route("/profile", get(get_profile))
    .layer(middleware::from_fn_with_state(state.clone(), auth_middleware));
```

## Installation

```toml
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
tower-http = { version = "0.6", features = ["cors", "trace"] }
tracing = "0.1"
tracing-subscriber = "0.3"
```

## Best Practices

1. **Extractors for everything** — State, Path, Query, Json, Headers — all type-checked at compile time
2. **Tower middleware** — Use Tower layers for cross-cutting concerns (CORS, tracing, rate limiting, compression)
3. **sqlx for database** — Compile-time checked SQL queries with `query_as!` macro; catches SQL errors before runtime
4. **Custom error types** — Implement `IntoResponse` for error enums; consistent error responses across all handlers
5. **Shared state via State** — Use `with_state()` for database pools, config, caches; cloned cheaply via Arc internally
6. **Graceful shutdown** — Use `tokio::signal` to handle SIGTERM; Axum drains connections before stopping
7. **WebSockets** — Axum has built-in WebSocket support via `extract::ws::WebSocket`; integrates with Tower middleware
8. **Performance** — Axum consistently tops TechEmpower benchmarks; zero-cost abstractions compile away at release

Related Skills

react-server-components-framework

25
from ComeOnOliver/skillshub

Design and implement React Server Components with Next.js 15 App Router. Master server-first architecture, streaming SSR, Server Actions, and modern data fetching patterns for 2025+ frontend development.

api-design-framework

25
from ComeOnOliver/skillshub

Use this skill when designing REST, GraphQL, or gRPC APIs. Provides comprehensive API design patterns, versioning strategies, error handling conventions, authentication approaches, and OpenAPI/AsyncAPI templates. Ensures consistent, well-documented, and developer-friendly APIs across all backend services.

rust-development

25
from ComeOnOliver/skillshub

Rust development best practices for the Guts project - idiomatic code, error handling, async patterns, and commonware integration

tool-selection-framework

25
from ComeOnOliver/skillshub

Design systematic decision frameworks for selecting appropriate AI tools (Claude Code vs Gemini CLI) based on context requirements, codebase size, reasoning depth needs, and task complexity. Use this skill when starting projects with unclear tool requirements, optimizing context-constrained workflows, or designing multi-phase strategies that leverage multiple tools' strengths. This skill helps match tool capabilities to task characteristics, preventing wasted context and ensuring optimal resource allocation.

content-evaluation-framework

25
from ComeOnOliver/skillshub

This skill should be used when evaluating the quality of book chapters, lessons, or educational content. It provides a systematic 6-category rubric with weighted scoring (Technical Accuracy 30%, Pedagogical Effectiveness 25%, Writing Quality 20%, Structure & Organization 15%, AI-First Teaching 10%, Constitution Compliance Pass/Fail) and multi-tier assessment (Excellent/Good/Needs Work/Insufficient). Use this during iterative drafting, after content completion, on-demand review requests, or before validation phases.

planning-framework

25
from ComeOnOliver/skillshub

Apply structured thinking before coding. Use when: starting new features, making architectural decisions, refactoring large components, or evaluating implementation approaches. Includes Musk's 5-step algorithm and ICE scoring framework.

rust-testing

25
from ComeOnOliver/skillshub

Rust测试模式,包括单元测试、集成测试、异步测试、基于属性的测试、模拟和覆盖率。遵循TDD方法学。

rust-patterns

25
from ComeOnOliver/skillshub

地道的Rust模式、所有权、错误处理、特质、并发,以及构建安全、高性能应用程序的最佳实践。

Yjs — CRDT Framework for Collaborative Editing

25
from ComeOnOliver/skillshub

## Overview

Turbopack — Rust-Powered Bundler for Next.js

25
from ComeOnOliver/skillshub

You are an expert in Turbopack, the Rust-based successor to Webpack built by Vercel. You help developers configure and optimize Turbopack for Next.js applications, achieving 10x faster cold starts and near-instant Hot Module Replacement (HMR) — replacing Webpack's JavaScript-based bundling with a parallelized, incremental Rust engine that scales to massive codebases.

Tokio — Async Runtime for Rust

25
from ComeOnOliver/skillshub

You are an expert in Tokio, the asynchronous runtime for Rust that powers most of the Rust async ecosystem. You help developers build high-performance network applications, concurrent services, and I/O-bound systems using Tokio's task scheduler, async I/O primitives, channels, timers, and synchronization utilities — handling millions of concurrent connections with minimal memory overhead.

TensorFlow — Deep Learning Framework

25
from ComeOnOliver/skillshub

You are an expert in TensorFlow, Google's open-source machine learning framework. You help developers build, train, and deploy neural networks using Keras (TensorFlow's high-level API), custom training loops, TensorFlow Serving for production inference, TFLite for mobile/edge deployment, and TensorFlow.js for browser ML — from prototyping to production-scale distributed training.