Skip to content
Axum Framework logo

Axum Framework

Ergonomic Rust web framework built on Tower and Tokio.

SKILL.md

Full skill instructions

Axum Standards

Router Setup

use axum::{Router, routing::{get, post}, Extension};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(root))
        .route("/​users", get(list_users).post(create_user))
        .route("/​users/:id", get(get_user))
        .nest("/​api", api_routes())
        .layer(Extension(db_pool))
        .layer(TraceLayer::new_for_http());

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

Extractors

use axum::{
    extract::{Path, Query, State, Json},
    http::StatusCode,
};

// Path parameters
async fn get_user(Path(id): Path<u64>) -> impl IntoResponse {
    Json(user)
}

// Query parameters
async fn list(Query(params): Query<Pagination>) -> impl IntoResponse {
    Json(items)
}

// JSON body
async fn create(Json(payload): Json<CreateUser>) -> impl IntoResponse {
    (StatusCode::CREATED, Json(user))
}

// State (shared application state)
async fn handler(State(pool): State<PgPool>) -> impl IntoResponse {
    let conn = pool.acquire().await?;
    Json(result)
}

State Management

#[derive(Clone)]
struct AppState {
    db: PgPool,
    cache: RedisPool,
}

let state = AppState { db, cache };

let app = Router::new()
    .route("/​users", get(handler))
    .with_state(state);

async fn handler(State(state): State<AppState>) -> impl IntoResponse {
    // Access state.db, state.cache
}

Error Handling

use axum::{
    response::{IntoResponse, Response},
    http::StatusCode,
};

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

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "Not found"),
            AppError::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Database error"),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

// Handler returns Result<T, AppError>
async fn handler() -> Result<Json<User>, AppError> {
    let user = db.find(id).await.map_err(AppError::Database)?;
    user.ok_or(AppError::NotFound).map(Json)
}

Middleware (Tower Layers)

use tower_http::{
    trace::TraceLayer,
    cors::CorsLayer,
    compression::CompressionLayer,
};

let app = Router::new()
    .route("/", get(handler))
    .layer(TraceLayer::new_for_http())
    .layer(CompressionLayer::new())
    .layer(CorsLayer::permissive());

// Custom middleware
async fn auth_layer<B>(
    req: Request<B>,
    next: Next<B>,
) -> Result<Response, StatusCode> {
    let token = req.headers().get("Authorization");
    // Validate token
    Ok(next.run(req).await)
}

Testing

use axum::http::StatusCode;
use axum_test::TestServer;

#[tokio::test]
async fn test_get_user() {
    let app = create_app();
    let server = TestServer::new(app).unwrap();

    let response = server.get("/​users/​1").await;

    assert_eq!(response.status_code(), StatusCode::OK);
}

Best Practices

  1. State: Use State<T> over Extension<T> for type safety
  2. Extractors: Order matters - put fallible extractors last
  3. Layers: Apply common layers at router level, not per-route
  4. Errors: Implement IntoResponse for custom error types

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View