liveBook · Manning

Axum

As explained in Code Like a Pro in Rust

axum is a Rust web framework for building HTTP server applications and routing requests to handlers.

Axum is a Rust web framework for building HTTP services on the Tokio async runtime. Its small, type-safe core is mostly macro-free and provides routing, extractors, responses, error handling, and integration with Tower. It uses hyper for HTTP/1 and HTTP/2. section 9.1 section 9.11

Use axum::Router to associate request paths and methods with handlers, supply state, and combine routes with service layers. A basic service does not require detailed Tower knowledge; deeper customization benefits from learning Tower. section 9.7 section 9.1

Declare API routes

A router can expose health checks and nest versioned endpoints: `Router::new().route("/alive", get(|| async { "ok" })).route("/ready", get(ping)).nest("/v1", Router::new().route("/todos", get(todo_list).post(todo_create)).route("/todos/:id", get(todo_read).put(todo_update).delete(todo_delete)))`. The `/todos/:id` route maps multiple methods to handlers for the same path. This syntax follows the example’s axum 0.6.18 dependency. section 9.7 section 9.4

Listing 9.11 API service router from src/router.rs
pub async fn create_router(
    dbpool: sqlx::Pool<sqlx::Sqlite>,                                 #1
) -> axum::Router {
    use crate::api::{
        ping, todo_create, todo_delete, todo_list, todo_read, todo_update,
    };
    use axum::{routing::get, Router};
    use tower_http::cors::{Any, CorsLayer};
    use tower_http::trace::TraceLayer;
 
    Router::new()
        .route("/alive", get(|| async { "ok" }))                      #2
        .route("/ready", get(ping))                                   #3
        .nest(
            "/v1",                                                    #4
            Router::new()
                .route("/todos", get(todo_list).post(todo_create))    #5
                .route(
                    "/todos/:id",
                    get(todo_read).put(todo_update)
 .delete(todo_delete),
                ),                                                    #6
        )
        .with_state(dbpool)                                           #7
        .layer(CorsLayer::new().allow_methods(Any)
 .allow_origin(Any))                                        #8
        .layer(TraceLayer::new_for_http())                            #9
}

Inspect the router example for its handler imports, database pool argument, health checks, and nested routes. section 9.7

Start a project with `cargo new api-server` and add the framework with `cargo add axum`. Add other crates as needed: the example uses Tokio for the runtime, SQLx for database access, and tower-http for tracing and CORS. Dependencies can be changed as the service evolves. section 9.4

Table 9.3 API service dependencies (view table figure)

Name

Features

Description

axum

Default

Web framework

chrono

serde

Date/time library, with serde feature

serde

derive

Serialization/deserialization library, with #[derive(...)] feature

serde_json

Default

JSON serialization/deserialization for the serde crate

sqlx

runtime-tokio-rustls, sqlite,chrono,macros

Async SQL toolkit for SQLite, MySQL, and PostgreSQL

tokio

macros,rt-multi-thread

Async runtime, used with axum and sqlx

tower-http

trace,cors

Provides HTTP middleware for axum, specifically, tracing and CORS

tracing

default

Async tracing library

tracing-subscriber

env-filter

Allows us to subscribe to tracing data within crates that use tracing

Review the example service’s dependency roles and feature selections. section 9.4

Keep service design separate from framework setup: choose a data model, state management, response formats, and architecture, then configure tracing and metrics for production. Consult axum’s documentation for framework features beyond the basic router. section 9.11 section 9.1 section 9.7

How Code Like a Pro in Rust covers it

How deep it goes
Demonstrates dependency setup and a basic router, while deferring deeper framework features to documentation.
Examples
Shows a versioned to-do API router with health checks and method-specific handlers.
What it assumes
Assumes an API design and handlers for the routing example, but does not require Tower internals for simple services.
What you can do after
Apply it via axum to declare routes and combine service components for a basic HTTP API.
How it connects
Connects routing to Tokio, Tower, hyper, SQLx, tracing, and CORS.

Also explained in

Compare how 2 books explain Axum →

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.