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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Splitting routes into sub-routers and nesting them under a prefix keeps large APIs organized and reusable.
- 2Custom fallbacks let you return consistent JSON error bodies instead of Axum's default plain responses.
- 3Any tuple of a status code and an extractor-friendly body can become a Response via IntoResponse.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/nesting-routers-and-json-fallbacks-in-axum-explained-rust-b52b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.