Axum Fit for REST JSON APIs

Learn why Axum is a natural choice for building REST APIs that communicate with JSON, with beginner-friendly examples and practical walkthroughs.

A REST JSON API is a web service that exposes data using predictable URL paths, standard HTTP methods, and JSON as the format for both requests and responses. Axum is particularly well suited for building these APIs because its design encourages small, focused handler functions, uses Rust's type system to validate incoming JSON automatically, and produces responses that integrate directly with standard HTTP tooling.

This page focuses on a single idea: why Axum feels natural when you are building a REST API that mostly sends and receives JSON, and what that looks like in real, runnable code. You will see how a basic JSON endpoint is created, how to read JSON from a request body, how to return different status codes, and how the pieces fit together without hidden magic.

What a REST JSON API Looks Like

Before looking at Axum specifically, it helps to fix a clear mental picture of the thing we are building. A REST API organizes data around resources. A resource is any meaningful object your application works with - a user, a product, an order, a blog post. Each resource gets a stable URL. A blog API might use paths like:

  • /posts - the collection of all posts
  • /posts/42 - one specific post
  • /posts/42/comments - comments attached to that post

The HTTP method on that URL says what action you want to perform. GET retrieves data, POST creates a new item, PUT or PATCH updates an existing item, and DELETE removes it. The important point here is that REST APIs use them in a very consistent, predictable way.

JSON (JavaScript Object Notation) is the data format most commonly used in these APIs. It is text-based, human-readable, and maps naturally to the structs and hashmaps programmers already use. A JSON response for a single blog post might look like this:

{
  "id": 42,
  "title": "Getting Started with Axum",
  "published": true,
  "tags": ["rust", "api", "backend"]
}

A client - a mobile app, a web frontend, another backend service - sends a request, receives this text, parses it back into its own data structures, and continues working. The server's job is to produce and consume this JSON correctly, consistently, and without making the client guess.

REST is a Style, Not a Protocol:

REST stands for Representational State Transfer. It is a set of design conventions for building web APIs, not a formal network protocol. Different teams apply the conventions slightly differently, but the core ideas - resources, URLs, HTTP methods, and representational formats like JSON - remain the same everywhere.

Why JSON APIs Are a Natural Fit for Axum

Axum does not force you to build REST JSON APIs. You can build other things with it, including plain HTML services, WebSocket backends, and static file servers. But when your goal is a JSON API, several of Axum's design decisions line up with exactly what you need, and they line up without extra ceremony.

The most important reason is Axum's type-driven extractor system. An extractor is a Rust type that tells Axum "I need this piece of information from the incoming request." A handler function declares the extractors it wants as parameters. When a request arrives, Axum looks at those parameter types, fetches the matching data from the HTTP request, and passes it to the handler. If any required piece is missing or invalid, Axum rejects the request before your handler ever runs.

For a JSON API, this means you can write a handler that expects Json<CreatePost>. The Json extractor reads the request body, checks that the Content-Type header says application/json, and attempts to deserialize the raw text into a CreatePost struct using the serde library. If the JSON is valid and the shape matches, the handler receives a properly typed Rust value. If the JSON is malformed, Axum automatically returns a 400 Bad Request response with a helpful error message - without you writing a single line of manual parsing code.

This combination of compile-time type checking and automatic runtime validation is precisely what makes JSON APIs safe to build and maintain. The Rust compiler verifies that your handler functions use types that actually exist and that your serde derive macros can produce and consume the JSON shapes you have declared. The runtime handles the messy reality of user input that may not match those shapes.

A Basic Starter Example

The smallest useful example is a single endpoint that returns JSON. No state, no database, no complicated routing - just a health check or a simple greeting. This establishes the core pattern before anything else is added.

Create a new Rust binary project and add the required dependencies to Cargo.toml:

[package]
name = "json-api-starter"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

The serde crate provides the Serialize and Deserialize traits. The derive feature enables the #[derive(Serialize, Deserialize)] macros, which automatically generate the code that converts between your Rust structs and JSON text. The tokio crate is the async runtime that Axum runs on.

Now the main file:

use axum::{routing::get, Json, Router};
use serde::Serialize;
#[derive(Serialize)]
struct HealthStatus {
    status: &'static str,
    version: &'static str,
}
async fn health_check() -> Json<HealthStatus> {
    Json(HealthStatus {
        status: "ok",
        version: env!("CARGO_PKG_VERSION"),
    })
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/health", get(health_check));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The HealthStatus struct has two fields, both string slices. The #[derive(Serialize)] attribute tells serde to generate the code that converts an instance of this struct into JSON text. The health_check handler returns Json<HealthStatus>, which tells Axum to serialize the inner value and attach the Content-Type: application/json response header automatically.

The Router is created with a single route: GET /health maps to the health_check function. The tokio::net::TcpListener binds to port 3000 on your local machine, and axum::serve starts the server. This is the full structure every Axum JSON endpoint follows, no matter how complex the API eventually becomes.

Run the program with cargo run, then open a second terminal and test it with curl:

curl http://127.0.0.1:3000/health

You will see output similar to this:

{"status":"ok","version":"0.1.0"}

The response is valid JSON, the content type is correct, and the client can parse it immediately. This simple flow - handler returns a typed value, Axum serializes it, the client receives JSON - is the foundation everything else builds on.

This Is the Correct Pattern:

If you see JSON output with the correct status and version fields, you have successfully created your first Axum JSON endpoint. The Content-Type header will be application/json, which is exactly what a REST client expects.

Reading JSON from the Request Body

Returning JSON is only half of a JSON API. Most REST services also need to accept data from clients, typically when creating or updating resources. Axum's Json extractor handles this in the opposite direction: it reads the raw request body, parses it as JSON, and gives your handler a strongly typed Rust value.

Start by defining a struct that represents the expected input. Derive Deserialize so serde can convert JSON text into the struct:

use axum::{routing::post, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreatePostRequest {
    title: String,
    content: String,
}
#[derive(Serialize)]
struct Post {
    id: u64,
    title: String,
    content: String,
}
async fn create_post(Json(payload): Json<CreatePostRequest>) -> Json<Post> {
    let post = Post {
        id: 1,
        title: payload.title,
        content: payload.content,
    };
    Json(post)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/posts", post(create_post));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The handler signature async fn create_post(Json(payload): Json<CreatePostRequest>) -> Json<Post> works like this. Axum sees that the handler expects a Json<CreatePostRequest>. It reads the request body, verifies that the Content-Type is application/json, and attempts to deserialize the body text into a CreatePostRequest. If all of that succeeds, it wraps the result in a Json value and passes it to the handler. The handler can then access payload.title and payload.content as normal Rust String fields.

Send a test request with curl:

curl -X POST http://127.0.0.1:3000/posts \
  -H "Content-Type: application/json" \
  -d '{"title":"Hello Axum","content":"This is my first post."}'

The response will look like:

{"id":1,"title":"Hello Axum","content":"This is my first post."}

What makes this powerful is the lack of manual parsing. In many frameworks, you would receive the raw request body as a string, then call a JSON parsing function, then check for errors, then manually extract each field. Axum condenses all of that into the type signature. The extraction happens before your handler runs, so the code inside the handler only deals with the happy path.

Wrong Content-Type Causes a 415 Error:

If the client sends a request without the Content-Type: application/json header, Axum's Json extractor rejects it with a 415 Unsupported Media Type status. This is correct behavior - the client must declare what format the body is in - but beginners often miss it. Always include the header when testing with curl or any HTTP client.

Handling Invalid JSON and Missing Fields

A real client will eventually send malformed JSON, missing fields, or fields of the wrong type. Axum handles these cases automatically because the Json extractor performs validation before the handler runs.

If the JSON body is not valid JSON at all, Axum returns 400 Bad Request. But if the JSON is valid and simply does not match the expected struct - a missing field, or a string where a number was expected - the status is 422 Unprocessable Entity, not 400. And the body is plain text, not a JSON object. (Unknown fields are a different case again: serde ignores them by default, so they cause no error at all unless you add #[serde(deny_unknown_fields)], in which case they are also a 422.)

The three cases, together with the wrong-Content-Type case, are:

What the client sentStatusDefault body
Malformed JSON syntax400 Bad RequestPlain text, e.g. Failed to parse the request body as JSON: …
Valid JSON, wrong shape (missing field, wrong type)422 Unprocessable EntityPlain text, e.g. Failed to deserialize the JSON body into the target type: missing field `content` at line 1 column 27
Missing or wrong Content-Type415 Unsupported Media TypePlain text, Expected request with Content-Type: application/json

For example, if you send this request to the previous example:

curl -X POST http://127.0.0.1:3000/posts \
  -H "Content-Type: application/json" \
  -d '{"title":"Missing content"}'

The response will have a 422 status and a plain-text body similar to this:

Failed to deserialize the JSON body into the target type: missing field `content` at line 1 column 27

This tells the client exactly what went wrong. More importantly, it happens without you writing any validation code. The struct definition itself is the validation rule. A field is required unless you declare it as an Option<T> type. A field's type is enforced unless you use a looser type like serde_json::Value.

Unknown Fields Are Ignored by Default:

If the client sends extra JSON fields that are not present in your struct, serde ignores them by default. This is usually fine, but if you need strict input validation that rejects unknown fields, you can add #[serde(deny_unknown_fields)] to the struct. Do not assume that unknown fields cause an error - by default they silently pass through.

Customising Json Errors, and Pagination and Validation

The default Json rejection is plain text. If your API promises JSON error bodies everywhere, take the rejection into the handler instead of letting Axum answer for you:

use axum::{
    extract::{rejection::JsonRejection, Json},
    http::StatusCode,
    response::IntoResponse,
};
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
struct CreatePostRequest {
    title: String,
    content: String,
}

async fn create_post(
    payload: Result<Json<CreatePostRequest>, JsonRejection>,
) -> impl IntoResponse {
    match payload {
        Ok(Json(post)) => (
            StatusCode::CREATED,
            Json(json!({ "title": post.title, "content": post.content })),
        )
            .into_response(),
        Err(JsonRejection::JsonSyntaxError(_)) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "malformed JSON" })),
        )
            .into_response(),
        Err(JsonRejection::JsonDataError(_)) => (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(json!({ "error": "JSON does not match the expected shape" })),
        )
            .into_response(),
        Err(JsonRejection::MissingJsonContentType(_)) => (
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            Json(json!({ "error": "expected Content-Type: application/json" })),
        )
            .into_response(),
        Err(_) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "could not read request body" })),
        )
            .into_response(),
    }
}

JsonRejection is #[non_exhaustive], so the match needs a catch-all arm. Its variants are JsonSyntaxError (400), JsonDataError (422), MissingJsonContentType (415), and BytesRejection (400). The other route to the same result is axum_extra::extract::WithRejection: declare WithRejection(Json(value), _): WithRejection<Json<CreatePostRequest>, ApiError> and implement From<JsonRejection> for ApiError, and the rejection becomes your own error type before the handler body runs.

Two things the Json extractor does not do for you, and that every real REST API has to add itself:

  • Pagination. There is no built-in pagination. The usual shape is a Query struct - page and per_page (or a cursor) - validated in the handler, with limit/offset applied to the query and the total count returned alongside the items, for example {"items": […], "page": 2, "per_page": 20, "total": 137}. Clamp per_page to a maximum (say 100) so one client cannot ask for the whole table, and reject page: 0 or negative values with a 400 from your own validation, not from the extractor.
  • Validation beyond shape. Serde checks shape - a field is present, and it is a string or a number. It cannot check meaning: that a title is non-empty, that an email looks like an email, or that a quantity is positive. For that, derive Validate from the validator crate on the same struct (with #[validate(length(min = 1))], #[validate(email)], #[validate(range(min = 1))] and similar attributes), call payload.validate() at the top of the handler, and return a 400 (or 422) with your own JSON error body when it fails. Keep the two layers separate in your head: serde rejects the wrong shape before the handler runs (422), your validation rejects the wrong values inside the handler (400/422, your choice - pick one and use it consistently).

A short serde-derives checklist for request and response structs: derive Deserialize on anything a client sends and Serialize on anything you return (both on a struct that does both); use #[serde(rename_all = "camelCase")] when your JSON field names differ from Rust's snake_case; use Option<T> for fields a client may omit, and #[serde(default)] when an omitted field should get a value rather than being an error; add #[serde(deny_unknown_fields)] only when you deliberately want unknown fields rejected (422) instead of ignored.

Building a Small But Complete REST JSON API

The starter examples show individual handlers. A real REST API combines many handlers around a single resource, each mapped to the appropriate HTTP method and URL pattern. Let's build a complete in-memory API for managing a list of notes. This demonstrates how all the pieces - GET, POST, PUT, DELETE - work together in one coherent service.

The API will support:

  • GET /notes - return all notes
  • POST /notes - create a new note
  • GET /notes/{id} - return one specific note
  • PUT /notes/{id} - replace a note's content
  • DELETE /notes/{id} - remove a note

First, the dependencies in Cargo.toml:

[package]
name = "notes-api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

Because multiple handlers need access to the same list of notes, we need shared state. In Rust, data shared between async tasks must be safe to access from multiple threads and safely mutable. The standard pattern is to wrap the data in Arc<Mutex<T>> - Arc provides shared ownership across threads, and Mutex provides safe interior mutability. The key point is that Axum handlers can receive this shared state through the State extractor.

Here is the complete program:

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::IntoResponse,
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone, Serialize)]
struct Note {
    id: u64,
    title: String,
    content: String,
}
#[derive(Deserialize)]
struct CreateNote {
    title: String,
    content: String,
}
#[derive(Deserialize)]
struct UpdateNote {
    title: String,
    content: String,
}
type SharedNotes = Arc<Mutex<HashMap<u64, Note>>>;
async fn list_notes(State(notes): State<SharedNotes>) -> Json<Vec<Note>> {
    let notes = notes.lock().unwrap();
    let mut result: Vec<Note> = notes.values().cloned().collect();
    result.sort_by_key(|note| note.id);
    Json(result)
}
async fn create_note(
    State(notes): State<SharedNotes>,
    Json(payload): Json<CreateNote>,
) -> (StatusCode, Json<Note>) {
    let mut notes = notes.lock().unwrap();
    let next_id = notes.keys().max().unwrap_or(&0) + 1;
    let note = Note {
        id: next_id,
        title: payload.title,
        content: payload.content,
    };
    notes.insert(next_id, note.clone());
    (StatusCode::CREATED, Json(note))
}
async fn get_note(
    State(notes): State<SharedNotes>,
    Path(id): Path<u64>,
) -> Result<Json<Note>, StatusCode> {
    let notes = notes.lock().unwrap();
    match notes.get(&id) {
        Some(note) => Ok(Json(note.clone())),
        None => Err(StatusCode::NOT_FOUND),
    }
}
async fn update_note(
    State(notes): State<SharedNotes>,
    Path(id): Path<u64>,
    Json(payload): Json<UpdateNote>,
) -> Result<Json<Note>, StatusCode> {
    let mut notes = notes.lock().unwrap();
    match notes.get_mut(&id) {
        Some(note) => {
            note.title = payload.title;
            note.content = payload.content;
            Ok(Json(note.clone()))
        }
        None => Err(StatusCode::NOT_FOUND),
    }
}
async fn delete_note(
    State(notes): State<SharedNotes>,
    Path(id): Path<u64>,
) -> StatusCode {
    let mut notes = notes.lock().unwrap();
    if notes.remove(&id).is_some() {
        StatusCode::NO_CONTENT
    } else {
        StatusCode::NOT_FOUND
    }
}
#[tokio::main]
async fn main() {
    let notes: SharedNotes = Arc::new(Mutex::new(HashMap::new()));
    let app = Router::new()
        .route("/notes", get(list_notes).post(create_note))
        .route("/notes/{id}", get(get_note).put(update_note).delete(delete_note))
        .with_state(notes);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Notes API running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This example ties together several important ideas. The SharedNotes type alias is an Arc<Mutex<HashMap<u64, Note>>>. The HashMap maps numeric IDs to Note values, giving fast lookup by ID. The Mutex allows safe mutation from multiple handlers, and the Arc ensures all handlers refer to the same underlying data.

Each handler receives State(notes): State<SharedNotes>. The State extractor pulls the shared data from the application state that was registered with .with_state(notes). Inside the handler, notes.lock().unwrap() acquires the mutex lock, giving exclusive access to the HashMap for the duration of the lock.

The handlers use different return types. list_notes returns Json<Vec<Note>>, which serializes the vector as a JSON array. create_note returns (StatusCode, Json<Note>), which lets you set the status to 201 Created while still returning the created resource. get_note and update_note return Result<Json<Note>, StatusCode>, which allows the handler to return either a successful JSON response or a bare status code for failure cases. delete_note returns only a StatusCode because 204 No Content and 404 Not Found both carry no body.

In-Memory Data Disappears on Restart:

This example stores notes in a HashMap that lives only in the program's memory. When the server stops, all data is lost. This is perfect for learning the API patterns, but a production service would use a database or other persistent storage layer. The REST patterns shown here remain the same regardless of where the data is actually stored.

Using Status Codes Correctly in a JSON API

The previous example already uses several different status codes. REST APIs rely heavily on status codes to communicate outcomes, and Axum makes it easy to return the right one for each situation. The key insight is that a JSON API should return JSON bodies for most responses, but the status code itself carries the primary success or failure signal.

Let's examine each status code used in the notes example and why it is there.

GET /notes returns 200 OK implicitly because Json<Vec<Note>> implements IntoResponse with that default status. POST /notes returns 201 Created because a new resource was successfully created - this is a signal to the client that the operation resulted in a new entity. PUT /notes/{id} returns 200 OK for a successful replacement. DELETE /notes/{id} returns 204 No Content because there is nothing to send back after deletion; the absence of a body is meaningful.

Error cases use 404 Not Found when the requested ID does not exist. The client can rely on this status code to determine that the resource was not available, without needing to parse a body to discover that fact.

You can also combine a status code with a JSON error body. A more detailed error response might look like this:

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::Serialize;
#[derive(Serialize)]
struct ApiError {
    error: &'static str,
    message: String,
}
fn not_found_response(id: u64) -> Response {
    let body = ApiError {
        error: "not_found",
        message: format!("Note with ID {} does not exist", id),
    };
    (StatusCode::NOT_FOUND, Json(body)).into_response()
}

This function returns a Response with status 404 and a JSON body. The client receives both the machine-readable status code and a human-readable, structured error message. This is common in production REST APIs where clients need to programmatically distinguish between different error conditions.

Returning 200 for Errors Confuses REST Clients:

A common beginner mistake is to return 200 OK with a JSON body like {"error": "not found"} when the resource does not exist. HTTP clients, monitoring tools, and caching layers all rely on the status code to understand the outcome. Use 404 for missing resources, 400 for bad input, and 500 for server errors, regardless of what the JSON body says.

Structuring a Realistic REST JSON API

The notes example keeps everything in one file, which is fine for learning. A larger API benefits from splitting code into modules, each responsible for one resource or one concern. This modularity is a natural fit for Axum's Router::nest method, which lets you mount a sub-router under a URL prefix.

A typical structure for a larger API might look like this:

src/
  main.rs
  routes/
    mod.rs
    notes.rs
    users.rs
  models/
    mod.rs
    note.rs
    user.rs
  error.rs
  state.rs

state.rs holds the shared state type - the same Arc<Mutex<HashMap<u64, Note>>> the single-file example called SharedNotes:

// state.rs
use crate::models::note::Note;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub type AppState = Arc<Mutex<HashMap<u64, Note>>>;

models/note.rs holds the same three structs from the single-file example, with pub on the structs and their fields - without it, routes/notes.rs could not construct a Note or read its fields. Each directory also needs a mod.rs declaring its modules (pub mod note; in models/mod.rs, pub mod notes; in routes/mod.rs):

// models/note.rs
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize)]
pub struct Note {
    pub id: u64,
    pub title: String,
    pub content: String,
}
#[derive(Deserialize)]
pub struct CreateNote {
    pub title: String,
    pub content: String,
}
#[derive(Deserialize)]
pub struct UpdateNote {
    pub title: String,
    pub content: String,
}

In this layout, routes/notes.rs defines a function that returns a Router handling all note-related endpoints. The handlers are the same five functions from the single-file example, with State<AppState> in place of State<SharedNotes>:

use axum::{
    extract::{Path, State},
    http::StatusCode,
    routing::get,
    Json, Router,
};
use crate::models::note::{CreateNote, Note, UpdateNote};
use crate::state::AppState;
pub fn notes_router() -> Router<AppState> {
    Router::new()
        .route("/", get(list_notes).post(create_note))
        .route("/{id}", get(get_note).put(update_note).delete(delete_note))
}
async fn list_notes(State(state): State<AppState>) -> Json<Vec<Note>> {
    let state = state.lock().unwrap();
    let mut result: Vec<Note> = state.values().cloned().collect();
    result.sort_by_key(|note| note.id);
    Json(result)
}
async fn create_note(
    State(state): State<AppState>,
    Json(payload): Json<CreateNote>,
) -> (StatusCode, Json<Note>) {
    let mut state = state.lock().unwrap();
    let next_id = state.keys().max().unwrap_or(&0) + 1;
    let note = Note {
        id: next_id,
        title: payload.title,
        content: payload.content,
    };
    state.insert(next_id, note.clone());
    (StatusCode::CREATED, Json(note))
}
async fn get_note(
    State(state): State<AppState>,
    Path(id): Path<u64>,
) -> Result<Json<Note>, StatusCode> {
    let state = state.lock().unwrap();
    match state.get(&id) {
        Some(note) => Ok(Json(note.clone())),
        None => Err(StatusCode::NOT_FOUND),
    }
}
async fn update_note(
    State(state): State<AppState>,
    Path(id): Path<u64>,
    Json(payload): Json<UpdateNote>,
) -> Result<Json<Note>, StatusCode> {
    let mut state = state.lock().unwrap();
    match state.get_mut(&id) {
        Some(note) => {
            note.title = payload.title;
            note.content = payload.content;
            Ok(Json(note.clone()))
        }
        None => Err(StatusCode::NOT_FOUND),
    }
}
async fn delete_note(
    State(state): State<AppState>,
    Path(id): Path<u64>,
) -> StatusCode {
    let mut state = state.lock().unwrap();
    if state.remove(&id).is_some() {
        StatusCode::NO_CONTENT
    } else {
        StatusCode::NOT_FOUND
    }
}

The main.rs file then assembles the top-level router by nesting these sub-routers:

mod models;
mod routes;
mod state;
use axum::Router;
use crate::state::AppState;
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
    let shared_state: AppState = Arc::new(Mutex::new(
        std::collections::HashMap::new(),
    ));
    let app = Router::new()
        .nest("/notes", routes::notes::notes_router())
        .with_state(shared_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This modular structure keeps each handler close to its resource, makes testing easier, and scales gracefully as the number of endpoints grows. The point is that Axum's Router is itself composable. A sub-router is just a value, and you can nest them to any depth, creating a tree of routes that mirrors your API's resource hierarchy.

Route Paths in Nested Routers Are Relative:

When you nest a router under /notes, the routes inside that sub-router are relative to the prefix. So route("/") inside notes_router responds to /notes, and route("/{id}") responds to /notes/{id}. This keeps each sub-router focused and readable.

Common Mistakes When Building JSON APIs with Axum

Several errors show up repeatedly when developers start building JSON APIs with Axum. Knowing them in advance saves time and frustration.

Forgetting to derive Serialize or Deserialize. If a struct is used as a response type but lacks Serialize, the compiler produces an error about the Serialize trait not being implemented. If a struct is used as a request body but lacks Deserialize, the error points to the Deserialize trait. These errors are clear enough, but they can be confusing the first time you encounter them.

Using the wrong Content-Type header. The Json extractor requires Content-Type: application/json on incoming requests. If the header is missing or set to something else, the request is rejected with 415 Unsupported Media Type. This is easy to miss when switching between HTTP clients.

Wrapping Json twice. A handler should return Json<T>, not Json<Json<T>>. Double-wrapping does not compile: the outer Json needs the inner value to implement Serialize, and axum's Json type does not implement Serialize at all - it is a response wrapper, not a plain data type. The compiler reports that Serialize is not implemented for Json<T>. Return Json<T> directly.

Locking the mutex and holding it across an await point. In the examples above, the mutex lock is always released before the handler returns, and there are no .await calls while the lock is held. Holding a std::sync::Mutex guard across an .await point is a common mistake: it compiles fine - the guard is Send when the guarded type is - but the worker thread stays blocked until the lock is released, so other requests stall and a second lock attempt from the same task deadlocks. For simple in-memory state, acquire the lock, do the work synchronously, and release it before any .await call.

Returning the wrong status code for the operation. Clients, monitoring systems, and intermediate proxies all depend on status codes. Using 200 OK for a POST that creates a resource, or returning 200 instead of 404 when a resource is missing, creates subtle bugs that are hard to diagnose because everything looks successful at the HTTP level.

Mutex Guard Across Await Blocks the Worker Thread:

In Rust, a std::sync::MutexGuard is Send when the guarded type is, so holding one across an .await point compiles - it does not trigger a "future cannot be sent between threads safely" error. The cost is at runtime instead: the worker thread running your handler stays blocked until the lock is released, so no other task on that thread makes progress, and a second lock attempt while the first is held deadlocks. Restructure your handler to release the lock before any .await. Use a separate scope block or extract the data you need from the lock before awaiting anything else.

When Axum Is a Good Choice for a REST JSON API

Axum is not the only Rust web framework, and it is not the right tool for every situation. But for a REST JSON API, several characteristics make it a strong default choice.

The handler signature is simple and explicit. A handler that reads JSON from the request body and returns JSON as a response has a type signature that reads almost like documentation. There is no hidden global state, no magic request object, no dynamic dispatch - just Rust types flowing through the system.

The extractor system scales naturally with API complexity. As endpoints grow from simple "return a constant" to "authenticate the user, validate the body, fetch data, return a composed response," you add more extractor types to the handler parameter list. Each extractor does one job, and they compose cleanly.

The error handling model is predictable. When a Json extractor fails, Axum returns a plain-text rejection before your handler runs - 400 for malformed syntax, 422 for a wrong shape, 415 for a wrong or missing Content-Type. There is no global extractor-error handler to customise this in one place: you customise it per handler, either by taking Result<Json<T>, JsonRejection> as the extractor argument and mapping the rejection yourself, or with axum_extra::extract::WithRejection, which turns the rejection into your own error type before the handler body runs. The default is sensible out of the box, and this consistency makes it easy to reason about what happens when a client sends bad data.

The ecosystem integration is practical. Axum works with tower-http middleware for common concerns like logging, CORS, compression, and request tracing. These are the kinds of cross-cutting concerns that every production JSON API eventually needs, and Axum's design makes them straightforward to add without changing individual handler logic.

Where Axum Adds Value Beyond Raw Framework Features

The practical advantage of Axum for JSON APIs becomes clearer when you consider what you do not have to write. In a lower-level HTTP library, you would manually read the request body into a buffer, check the content type, call a JSON parser, handle each possible parsing error, build a response with the correct headers, and serialize the response body yourself. Axum collapses all of that into a handler signature and the Json type.

This does not mean Axum hides everything behind magic. The source code is straightforward to inspect, and the layers are visible when you need them. The Json extractor is a small piece of code built on serde. The Router is a thin layer over tower services. The runtime is Tokio. When you need to understand what is happening, you can follow the trail.

That transparency is a significant advantage for a team building and maintaining a long-lived API. There are fewer hidden mechanisms that break in surprising ways, and more of the system can be reasoned about directly from the type signatures.

Building Confidence Through Incremental Expansion

The best way to learn how Axum fits REST JSON APIs is to build one incrementally. Start with a single GET endpoint that returns a hardcoded JSON value. Then add a POST endpoint that reads a JSON body and stores it in memory. Then add a dynamic path parameter with Path<u64> to retrieve a single item. Then add PUT and DELETE handlers, observing how the status codes differ. Finally, split the code into modules and nest the routers.

At each step, test with curl and observe both the status code and the response body. The status code tells you whether the operation succeeded or failed. The body tells you what data was returned or what went wrong. This dual observation habit is the foundation of debugging any REST API, regardless of language or framework.

Small Steps Build Reliable Mental Models:

If you can build the notes API from scratch and explain why each handler returns the type it does, you have internalized the core pattern of Axum JSON APIs. Every larger JSON service is a composition of these same small pieces - handlers, extractors, routers, and JSON serialization.

Summary

Axum's fit for REST JSON APIs comes from an alignment between what such APIs require and what Axum's design naturally provides. JSON APIs need to receive and return structured data with clear error boundaries. Axum's type-driven extractors and Json response type handle this with minimal boilerplate. JSON APIs need many small, composable endpoints organized around resources. Axum's Router and nest mechanism reflect this structure directly. JSON APIs need predictable behavior when input is invalid. Axum's default error handling delivers that predictability without extra configuration.

The most important insight is not a specific API call or code pattern - it is a way of thinking. In Axum, you express the shape of your JSON API through Rust types, and you let the framework handle the mechanical work of converting between HTTP bytes and typed values. This type-first approach is what makes Axum feel natural for REST JSON APIs.