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
ruby
require "net/http" require "json" require "uri" require "base64"
Paginating an HTTP API with a Ruby enumerator
pagination
http
enumerator
Intermediate
7 steps
java
@Configuration @EnableKafka public class KafkaErrorHandlingConfig {
Kafka retry and dead-letter handling in Spring
kafka
error-handling
retry
Intermediate
7 steps
rust
use axum::{ extract::FromRequestParts, http::{request::Parts, StatusCode, header::ACCEPT_LANGUAGE}, };
A locale extractor for Axum handlers
content-negotiation
http-headers
custom-extractor
Intermediate
7 steps
go
package admin import ( "net/http"
Building a protected admin area in Gin
routing
middleware
authentication
Intermediate
6 steps
rust
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time::Duration;
Graceful thread shutdown with an atomic flag
concurrency
atomics
memory-ordering
Advanced
7 steps
go
package middleware import ( "errors"
Capping request body size in Gin
middleware
request limits
error handling
Intermediate
5 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.