Course › Week 5 · Axum microservice › Day 1 · lesson 29 of 42 · 20 min reading + 45–60 min practice
Routing and handlers
An axum Router, handlers, and path and query extractors.
On this page
Week 4’s worker is started by Laravel for one job and exits. This week’s tool is the other shape from the Process lesson’s table: a service that runs all the time and answers HTTP requests, for work that is called many times a day in small pieces, or by more than one app.
axum is the web framework from the tokio team, and the most used one in new Rust services. It feels close to Laravel’s router: a route, a method, a handler. What is new is that the handler’s arguments say what it needs from the request, and axum checks the request against them before your code runs.
Every server on this page was started for real; each response below is what curl -si printed, with only the date: header removed because it changes every second. The server’s own log is shown after it was stopped with Ctrl-C.
1. The smallest service
A Router maps paths to handlers. TcpListener::bind opens the port, axum::serve runs the router on it, and with_graceful_shutdown stops it cleanly on Ctrl-C: requests already in progress finish first.
use std::error::Error;
use axum::Router;
use axum::routing::get;
use tokio::net::TcpListener;
async fn health() -> &'static str {
"ok"
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/health", get(health));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
eprintln!("listening on http://127.0.0.1:3000");
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
eprintln!("stopped");
Ok(())
}
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 2
okHTTP/1.1 404 Not Found
content-length: 0listening on http://127.0.0.1:3000
stoppedA handler is any async fn whose arguments and return type axum knows how to handle. A route that does not exist gets an empty 404 for free, like a missing route in Laravel.
axum::serve(...).await only returns when the server stops, which is why stopped appears in the log after Ctrl-C.
2. What a handler can return
Anything that implements IntoResponse. Text becomes text/plain. Json(value) serialises with serde and sets application/json. A tuple with a StatusCode first sets the status. Most handlers return one of these three:
use std::error::Error;
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use tokio::net::TcpListener;
#[derive(Serialize)]
struct Version {
name: &'static str,
version: &'static str,
}
async fn version() -> Json<Version> {
Json(Version {
name: "evaluation-service",
version: "0.1.0",
})
}
async fn maintenance() -> (StatusCode, &'static str) {
(StatusCode::SERVICE_UNAVAILABLE, "down for maintenance")
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new()
.route("/version", get(version))
.route("/maintenance", get(maintenance));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
eprintln!("listening on http://127.0.0.1:3000");
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
eprintln!("stopped");
Ok(())
}
HTTP/1.1 200 OK
content-type: application/json
content-length: 47
{"name":"evaluation-service","version":"0.1.0"}HTTP/1.1 503 Service Unavailable
content-type: text/plain; charset=utf-8
content-length: 20
down for maintenancelistening on http://127.0.0.1:3000
stoppedJson(…) is Laravel’s response()->json(…), and (StatusCode::CREATED, Json(…)) is response()->json(…, 201). The status is a named constant, so StatusCode::SERVICE_UNAVAILABLE cannot be mistyped as 530.
3. Path: values from the URL
{id} in the route is a path parameter, like {booking} in a Laravel route. The handler asks for it with Path(id): Path<u64>: an extractor. The pattern Path(id) takes the value out of the wrapper right in the argument list. The type is the validation: a path that is not a number never reaches the handler.
use std::error::Error;
use axum::extract::Path;
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use tokio::net::TcpListener;
/// Stands in for the database until the shared-state lesson.
const BOOKINGS: [(u64, &str, u32, &str); 3] = [
(5521, "Lina", 3, "confirmed"),
(5522, "Omar", 7, "pending"),
(5523, "Sara", 2, "confirmed"),
];
#[derive(Serialize)]
struct Booking {
id: u64,
guest: &'static str,
nights: u32,
status: &'static str,
}
async fn show(Path(id): Path<u64>) -> Result<Json<Booking>, StatusCode> {
let (id, guest, nights, status) = BOOKINGS
.into_iter()
.find(|(booking_id, ..)| *booking_id == id)
.ok_or(StatusCode::NOT_FOUND)?;
Ok(Json(Booking {
id,
guest,
nights,
status,
}))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/bookings/{id}", get(show));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
eprintln!("listening on http://127.0.0.1:3000");
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
eprintln!("stopped");
Ok(())
}
HTTP/1.1 200 OK
content-type: application/json
content-length: 56
{"id":5522,"guest":"Omar","nights":7,"status":"pending"}HTTP/1.1 404 Not Found
content-length: 0HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 42
Invalid URL: Cannot parse `abc` to a `u64`listening on http://127.0.0.1:3000
stoppedA handler can return a Result: Ok is the response, and Err is a response too, as long as both implement IntoResponse. So ? works in handlers. Here a missing booking becomes an empty 404; the errors lesson gives it a JSON body like Laravel’s.
abc was rejected with 400 and a sentence, before show ran. (booking_id, ..) matches a tuple by its first item and ignores the rest.
4. Query: values from the query string
Query<T> decodes the query string into a struct with serde. Option fields are optional parameters, and #[serde(default)] gives the others a default, like $request->query('page', 1).
use std::error::Error;
use axum::extract::Query;
use axum::routing::get;
use axum::{Json, Router};
use serde::Deserialize;
use tokio::net::TcpListener;
/// Stands in for the database until the shared-state lesson.
const BOOKINGS: [(u64, &str, u32, &str); 3] = [
(5521, "Lina", 3, "confirmed"),
(5522, "Omar", 7, "pending"),
(5523, "Sara", 2, "confirmed"),
];
#[derive(Deserialize)]
struct Filters {
status: Option<String>,
#[serde(default)]
min_nights: u32,
}
async fn index(Query(filters): Query<Filters>) -> Json<Vec<u64>> {
let ids = BOOKINGS
.into_iter()
.filter(|(_, _, nights, _)| *nights >= filters.min_nights)
.filter(|(_, _, _, status)| {
filters
.status
.as_deref()
.is_none_or(|wanted| wanted == *status)
})
.map(|(id, ..)| id)
.collect();
Json(ids)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/bookings", get(index));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
eprintln!("listening on http://127.0.0.1:3000");
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
eprintln!("stopped");
Ok(())
}
HTTP/1.1 200 OK
content-type: application/json
content-length: 16
[5521,5522,5523]HTTP/1.1 200 OK
content-type: application/json
content-length: 11
[5521,5523]HTTP/1.1 200 OK
content-type: application/json
content-length: 6
[5521]HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 77
Failed to deserialize query string: min_nights: invalid digit found in stringlistening on http://127.0.0.1:3000
stoppedis_none_or(…) is true when the filter was not given, or when the closure says the value matches: “no status filter, or the right status”, in one call.
min_nights=many is a 400 with the reason. In Laravel, (int) $request->query('min_nights') would quietly have been 0, and every booking would have matched.
5. Methods, and grouping under /api
Several methods on one path chain on the route: get(index).post(store). A known path with the wrong method gets 405 with an allow header, as in Laravel. nest("/api", …) mounts a whole router under a prefix, like Route::prefix('api')->group(…).
use std::error::Error;
use axum::Router;
use axum::http::StatusCode;
use axum::routing::get;
use tokio::net::TcpListener;
async fn index() -> &'static str {
"the bookings"
}
async fn store() -> (StatusCode, &'static str) {
(StatusCode::CREATED, "created")
}
async fn health() -> &'static str {
"ok"
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let api = Router::new().route("/bookings", get(index).post(store));
let app = Router::new()
.route("/health", get(health))
.nest("/api", api);
let listener = TcpListener::bind("127.0.0.1:3000").await?;
eprintln!("listening on http://127.0.0.1:3000");
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
eprintln!("stopped");
Ok(())
}
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 12
the bookingsHTTP/1.1 201 Created
content-type: text/plain; charset=utf-8
content-length: 7
createdHTTP/1.1 405 Method Not Allowed
allow: GET,HEAD,POST
content-length: 0HTTP/1.1 404 Not Found
content-length: 0listening on http://127.0.0.1:3000
stopped/bookings without the prefix is a 404: the route exists only under /api. HEAD is allowed automatically wherever GET is.
The same routes in Laravel
<?php
use App\Http\Controllers\BookingController;
use Illuminate\Support\Facades\Route;
Route::get('/bookings', [BookingController::class, 'index']);
Route::post('/bookings', [BookingController::class, 'store']);
Route::get('/bookings/{id}', [BookingController::class, 'show'])->whereNumber('id');
Almost line for line. The difference is where the request is checked: Laravel gives the controller a Request and the code reads from it ($request->query('min_nights')), so a wrong type shows up wherever it is used. In axum the handler’s arguments are the contract, Path<u64>, Query<Filters>, and a request that does not fit them gets a 400 before any of your code runs.
PracticeThe axum docs, and pagination
Read the front page of the axum docs, sections “Routing”, “Handlers” and “Extractors”.
Exercise: pages
Add page and per_page to the query (defaults 1 and 2, per_page at most 50) and return {"data": [...], "current_page": 1, "last_page": 2, "total": 3}, the shape of a Laravel paginator, so the Laravel side could read it with the same code it uses for its own APIs.
Show the solution
use std::error::Error;
use axum::extract::Query;
use axum::routing::get;
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;
/// Stands in for the database until the shared-state lesson.
const BOOKINGS: [(u64, &str, u32, &str); 3] = [
(5521, "Lina", 3, "confirmed"),
(5522, "Omar", 7, "pending"),
(5523, "Sara", 2, "confirmed"),
];
#[derive(Deserialize)]
struct PageQuery {
#[serde(default = "first_page")]
page: usize,
#[serde(default = "two")]
per_page: usize,
}
fn first_page() -> usize {
1
}
fn two() -> usize {
2
}
#[derive(Serialize)]
struct Page {
data: Vec<u64>,
current_page: usize,
last_page: usize,
total: usize,
}
async fn index(Query(q): Query<PageQuery>) -> Json<Page> {
let per_page = q.per_page.clamp(1, 50);
let total = BOOKINGS.len();
let last_page = total.div_ceil(per_page).max(1);
let page = q.page.clamp(1, last_page);
let data = BOOKINGS
.into_iter()
.skip((page - 1) * per_page)
.take(per_page)
.map(|(id, ..)| id)
.collect();
Json(Page {
data,
current_page: page,
last_page,
total,
})
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/bookings", get(index));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
eprintln!("listening on http://127.0.0.1:3000");
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
eprintln!("stopped");
Ok(())
}
HTTP/1.1 200 OK
content-type: application/json
content-length: 61
{"data":[5521,5522],"current_page":1,"last_page":2,"total":3}HTTP/1.1 200 OK
content-type: application/json
content-length: 56
{"data":[5523],"current_page":2,"last_page":2,"total":3}HTTP/1.1 200 OK
content-type: application/json
content-length: 66
{"data":[5521,5522,5523],"current_page":1,"last_page":1,"total":3}listening on http://127.0.0.1:3000
stopped#[serde(default = "first_page")] names a function that gives the default, for defaults other than 0. clamp keeps a value inside a range, so page=9 and per_page=500 become the last page and 50 instead of an empty page or a 500-row response. div_ceil divides and rounds up: 3 bookings, 2 per page, 2 pages.
Remember
- A handler is an async function: extractors in, anything that is
IntoResponseout. - A path or query that does not parse is rejected before your code runs; type the parameters and let axum answer 400.
Tomorrow: JSON request bodies, and validation that answers like a Laravel Form Request.