rust 55 lines · 7 steps

Nesting routers and JSON fallbacks in Axum

An Axum app composes a nested API router with typed handlers and custom 404 and 405 responses that always return JSON.

Explained by highlit
1use axum::{
2 body::Body,
3 http::{Method, StatusCode, Uri},
4 response::{IntoResponse, Response},
5 routing::{get, post, MethodRouter},
6 Json, Router,
7};
8use serde_json::json;
9 
10fn api_router() -> Router {
11 Router::new()
12 .route("/users", get(list_users).post(create_user))
13 .route("/users/{id}", get(get_user))
14 .method_not_allowed_fallback(method_not_allowed)
15}
16 
17pub fn app() -> Router {
18 Router::new()
19 .nest("/api", api_router())
20 .fallback(not_found)
21}
22 
23async fn method_not_allowed(method: Method, uri: Uri) -> Response {
24 (
25 StatusCode::METHOD_NOT_ALLOWED,
26 Json(json!({
27 "error": "method_not_allowed",
28 "message": format!("{method} is not supported on {}", uri.path()),
29 })),
30 )
31 .into_response()
32}
33 
34async fn not_found(uri: Uri) -> Response {
35 (
36 StatusCode::NOT_FOUND,
37 Json(json!({
38 "error": "not_found",
39 "message": format!("No route matches {}", uri.path()),
40 })),
41 )
42 .into_response()
43}
44 
45async fn list_users() -> impl IntoResponse {
46 Json(json!({ "users": [] }))
47}
48 
49async fn create_user() -> impl IntoResponse {
50 StatusCode::CREATED
51}
52 
53async fn get_user() -> impl IntoResponse {
54 Json(json!({ "user": null }))
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Splitting routes into sub-routers and nesting them under a prefix keeps large APIs organized and reusable.
  2. 2Custom fallbacks let you return consistent JSON error bodies instead of Axum's default plain responses.
  3. 3Any tuple of a status code and an extractor-friendly body can become a Response via IntoResponse.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Nesting routers and JSON fallbacks in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code