Nine parts in, we're finally building a web server. Everything so far has been leading here: structs and enums to model data, Result for errors, traits and generics, iterators, and last time, async with Tokio. From this part to the end of the series, we'll build one application and keep improving it until it's deployed.
The application is called linkbox. It's a JSON API for saving bookmarks: each link has a URL, a title and some tags. It's small enough to understand completely, but it touches everything a real API needs: routing, validation, a database, authentication, tests and deployment.
We're using Axum, which I picked in the framework comparison for being the most common choice for new projects and having the most approachable design. This part covers routes, handlers, reading data out of requests with extractors, JSON in and out with serde, and status codes. There's no shared state or database yet. The list of links is hard-coded, and the next part fixes that.
Everything below ran on Rust 1.100.0 with Axum 0.8.9 and Tokio 1.54.1, and every response shown came from curl against the running server.
Setting up
cargo new linkbox
cd linkbox
cargo add axum
cargo add tokio --features full
cargo add serde --features derive
cargo add serde_json
That gives this Cargo.toml:
[package]
name = "linkbox"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8.9"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
tokio = { version = "1.54.1", features = ["full"] }
Four direct dependencies, which pull in 55 crates in total. The first build takes a minute or so while Cargo compiles them all. After that, rebuilds only compile your code.
Hello, Axum
The smallest useful Axum app:
use axum::{Router, routing::get};
async fn root() -> &'static str {
"linkbox is running"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(root));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
curl -i http://127.0.0.1:3000/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 18
date: Tue, 01 Dec 2026 06:48:32 GMT
linkbox is running
Compare it with the raw TCP server from part 9. The shape is the same: bind a listener, then serve connections forever. The difference is that axum::serve parses HTTP properly, handles keep-alive and request bodies, and sends each request to the right function based on its path and method.
Here's the Express equivalent, so you can line them up:
import express from "express";
const app = express();
app.get("/", (req, res) => res.send("linkbox is running"));
app.listen(3000, () => console.log("listening on 3000"));
Three pieces map across directly:
Router::new()isexpress(). It holds the routes..route("/", get(root))isapp.get("/", handler). The method is a function wrapping the handler, soget(root),post(create), and so on.axum::serve(listener, app)isapp.listen(3000). The listener is a TokioTcpListener, so you control the address, and it's the same type you'd use anywhere else in Tokio.
I bind to 0.0.0.0 rather than 127.0.0.1 because the server will run inside a Docker container in part 15, and a container's 127.0.0.1 isn't reachable from outside it. During development either works.
Handlers
A handler is an async function that Axum calls for a request. Notice what root doesn't have: there's no req or res parameter. It takes no arguments and returns a string. Axum turns the return value into a response.
That's the core of how Axum works, and it's the biggest difference from Express. In Express, every handler gets the whole request and a response object, and you call methods on res to send something. In Axum:
- The arguments say what the handler needs from the request. Each argument is an extractor that pulls one thing out: a path parameter, the query string, the JSON body, a header.
- The return type says what the response is. Anything that implements the
IntoResponsetrait can be returned: strings, JSON, status codes, tuples of those, and your own types.
So a handler's signature documents exactly what it reads and what it can send back, and the compiler checks both.
Returning JSON
Here's the data type for linkbox:
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
struct Link {
id: u64,
url: String,
title: String,
tags: Vec<String>,
}
#[derive(Serialize)] comes from serde, Rust's serialisation library. It generates code that turns a Link into JSON (or many other formats). Because it's generated at compile time for this exact struct, there's no reflection at runtime, and it's fast.
Until we have a database, some hard-coded links:
fn sample_links() -> Vec<Link> {
let link = |id, url: &str, title: &str, tags: &[&str]| Link {
id,
url: url.to_string(),
title: title.to_string(),
tags: tags.iter().map(|t| t.to_string()).collect(),
};
vec![
link(1, "https://www.rust-lang.org", "Rust", &["rust"]),
link(2, "https://tokio.rs", "Tokio", &["rust", "async"]),
link(3, "https://developer.mozilla.org", "MDN", &["web", "docs"]),
]
}
(The link closure is just a shortcut to avoid writing .to_string() a dozen times.)
To send JSON, wrap the value in Json:
use axum::Json;
async fn list_links() -> Json<Vec<Link>> {
Json(sample_links())
}
Json<T> implements IntoResponse for any T that implements Serialize. It serialises the value and sets content-type: application/json.
For one-off JSON, where defining a struct feels like overkill, serde_json::json! builds a value inline, with syntax that looks like a JavaScript object:
async fn health() -> Json<serde_json::Value> {
Json(serde_json::json!({ "status": "ok", "version": env!("CARGO_PKG_VERSION") }))
}
{"status":"ok","version":"0.1.0"}
env!("CARGO_PKG_VERSION") reads the version from Cargo.toml at compile time, which is a handy thing to have in a health check when you're trying to work out which build is deployed.
What happens if you forget Serialize
If you leave the derive off, you get an error that looks like it's about something else entirely:
error[E0277]: the trait bound `fn() -> impl Future<Output = Json<Link>> {link}: Handler<_, _>` is not satisfied
--> src/bin/e_serialize.rs:12:57
|
12 | let _app: Router = Router::new().route("/link", get(link));
| --- ^^^^ the trait `Handler<_, _>` is not implemented for fn item `fn() -> impl Future<Output = Json<Link>> {link}`
| |
| required by a bound introduced by this call
|
= note: Consider using `#[axum::debug_handler]` to improve the error message
"Handler is not implemented" is the error you'll see for almost any mistake in a handler's signature. It means "this function doesn't fit the shape Axum expects", without saying why, because of how the trait machinery works. The note at the bottom is the way out. Add the macros feature to axum (cargo add axum --features macros), and put #[debug_handler] on the handler:
use axum::debug_handler;
#[debug_handler]
async fn link() -> Json<Link> {
Json(Link { id: 1 })
}
error[E0277]: the trait bound `Link: serde::Serialize` is not satisfied
--> src/bin/e_serialize2.rs:8:20
|
8 | async fn link() -> Json<Link> {
| ^^^^ unsatisfied trait bound
|
help: the trait `serde_core::ser::Serialize` is not implemented for `Link`
--> src/bin/e_serialize2.rs:3:1
|
3 | struct Link {
| ^^^^^^^^^^^
= note: for local types consider adding `#[derive(serde::Serialize)]` to your `Link` type
Now it points at the real problem. #[debug_handler] does nothing at runtime and only exists to improve error messages, so I add it whenever a handler won't compile and I can't see why.
Path parameters
A route to get one link by its id:
use axum::{extract::Path, http::StatusCode};
async fn get_link(Path(id): Path<u64>) -> Result<Json<Link>, StatusCode> {
sample_links()
.into_iter()
.find(|link| link.id == id)
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
}
And in the router:
.route("/links/{id}", get(get_link))
There's a lot going on in that handler, so piece by piece.
{id} in the route is a path parameter, like :id in Express.
Path(id): Path<u64> is the extractor. The type says "parse the path parameter as a u64". The Path(id) on the left is a pattern, like the destructuring from part 4: Path is a struct wrapping one value, and the pattern unwraps it so id is a plain u64 inside the function.
The return type is Result<Json<Link>, StatusCode>. Result implements IntoResponse when both sides do, so returning Ok(json) sends the link and Err(StatusCode::NOT_FOUND) sends an empty 404.
The body is an iterator chain from part 8: find the link, wrap it in Json if found, and turn None into the error with ok_or.
curl http://127.0.0.1:3000/links/2
{"id":2,"url":"https://tokio.rs","title":"Tokio","tags":["rust","async"]}
curl -i http://127.0.0.1:3000/links/99
HTTP/1.1 404 Not Found
content-length: 0
And here's the part I like:
curl -i http://127.0.0.1:3000/links/abc
HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 42
Invalid URL: Cannot parse `abc` to a `u64`
We didn't write that. Because the handler asked for a u64, Axum tried to parse it, failed, and responded with a 400 before our function ever ran. In Express, req.params.id is always a string. You have to remember to call Number() or parseInt, then check for NaN, in every handler. Here, if the code inside the handler runs, id is a valid number.
These automatic error responses are called rejections. The plain text messages are fine for now. Part 11 replaces them with consistent JSON errors.
The old colon syntax
If you follow an older Axum tutorial, you'll see routes written as "/links/:id". That was the syntax up to Axum 0.7. In 0.8 it changed to {id}, and the old style fails loudly when the router is built:
thread 'main' (987) panicked at src/bin/e_colon.rs:8:38:
Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router.
It panics at startup, not on the first request, so you'll find out right away. Wildcards changed the same way, from *rest to {*rest}.
Query parameters
To filter the list by tag and limit how many come back, like /links?tag=rust&limit=1, describe the query string as a struct:
#[derive(Debug, Deserialize)]
struct ListParams {
tag: Option<String>,
#[serde(default = "default_limit")]
limit: usize,
}
fn default_limit() -> usize {
10
}
Then use the Query extractor:
use axum::extract::Query;
async fn list_links(Query(params): Query<ListParams>) -> Json<Vec<Link>> {
let links = sample_links()
.into_iter()
.filter(|link| match ¶ms.tag {
Some(tag) => link.tags.contains(tag),
None => true,
})
.take(params.limit)
.collect();
Json(links)
}
Deserialize is the other half of serde: it builds a value of your type from incoming data. The struct says exactly which parameters exist and what types they have. tag is an Option, so it's optional, and None when missing. limit is required by its type, but #[serde(default = "default_limit")] fills in 10 when it's left out.
curl "http://127.0.0.1:3000/links?tag=rust"
[{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"]},{"id":2,"url":"https://tokio.rs","title":"Tokio","tags":["rust","async"]}]
curl "http://127.0.0.1:3000/links?tag=rust&limit=1"
[{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"]}]
And a bad value is rejected before the handler runs, just like the path:
curl "http://127.0.0.1:3000/links?limit=lots"
Failed to deserialize query string: limit: invalid digit found in string
In Express, req.query.limit would be the string "lots", and arr.slice(0, "lots") would quietly return an empty array. No error, just wrong data. That's the sort of bug that types make impossible.
Accepting JSON
Creating a link means reading a JSON body. The input type is different from Link, because the client shouldn't choose the id:
#[derive(Debug, Deserialize)]
struct NewLink {
url: String,
title: String,
#[serde(default)]
tags: Vec<String>,
}
#[serde(default)] on tags means it can be left out, and an empty Vec is used instead.
Having separate types for input and output is a pattern you'll see in most Rust APIs. It's more typing than reusing one type, but each one says exactly what it means. NewLink is what a client may send. Link is what the server stores and returns. When we add a created_at field later, the client won't be able to set it, because it won't be in NewLink.
The handler:
async fn create_link(Json(input): Json<NewLink>) -> (StatusCode, Json<Link>) {
let link = Link {
id: 4,
url: input.url,
title: input.title,
tags: input.tags,
};
(StatusCode::CREATED, Json(link))
}
Json works in both directions: as an argument, it's an extractor that parses the body. As a return value, it serialises.
The return type is a tuple of a status code and a body. Tuples like this implement IntoResponse, with the status first, so this sends a 201 with JSON. The id is always 4 for now, because we have nowhere to store anything. Part 11 adds that.
Routes with several methods chain them:
.route("/links", get(list_links).post(create_link))
Trying it:
curl -i -X POST http://127.0.0.1:3000/links \
-H 'content-type: application/json' \
-d '{"url":"https://axum.rs","title":"Axum","tags":["rust","web"]}'
HTTP/1.1 201 Created
content-type: application/json
content-length: 69
{"id":4,"url":"https://axum.rs","title":"Axum","tags":["rust","web"]}
Leaving out tags:
curl -X POST http://127.0.0.1:3000/links \
-H 'content-type: application/json' \
-d '{"url":"https://serde.rs","title":"Serde"}'
{"id":4,"url":"https://serde.rs","title":"Serde","tags":[]}
Bad input, handled for free
What about the many ways a client can get this wrong? A missing field:
curl -i -X POST http://127.0.0.1:3000/links \
-H 'content-type: application/json' \
-d '{"url":"https://serde.rs"}'
HTTP/1.1 422 Unprocessable Entity
content-type: text/plain; charset=utf-8
content-length: 99
Failed to deserialize the JSON body into the target type: missing field `title` at line 1 column 26
Broken JSON:
curl -i -X POST http://127.0.0.1:3000/links \
-H 'content-type: application/json' \
-d '{"url":"https://serde.rs",'
HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 87
Failed to parse the request body as JSON: EOF while parsing a value at line 1 column 26
No content type header:
curl -i -X POST http://127.0.0.1:3000/links \
-d '{"url":"https://serde.rs","title":"Serde"}'
HTTP/1.1 415 Unsupported Media Type
content-type: text/plain; charset=utf-8
content-length: 54
Expected request with `Content-Type: application/json`
Three different mistakes, three correct status codes, and our handler wasn't involved in any of them. In Express you need express.json() middleware for the body to be parsed at all, and then something like Zod or Joi to check its shape, because req.body could be anything. Here, the type of the argument is the schema. If create_link runs, input.url and input.title are strings and input.tags is a list of strings.
What serde doesn't check is meaning. An empty title or a URL of "not a url" would get through. Validation of values is part 13.
Methods and fallbacks
Axum handles a couple more cases on its own. A method that isn't registered for a path:
curl -i -X DELETE http://127.0.0.1:3000/links
HTTP/1.1 405 Method Not Allowed
allow: GET,HEAD,POST
content-length: 0
That's the correct status, with an allow header listing what is supported. HEAD is included because Axum answers HEAD for every GET route automatically. Express would have sent a 404 here.
For paths that don't match any route, Axum sends an empty 404 by default. fallback lets you choose the response:
async fn not_found() -> (StatusCode, &'static str) {
(StatusCode::NOT_FOUND, "nothing here")
}
HTTP/1.1 404 Not Found
content-type: text/plain; charset=utf-8
content-length: 12
nothing here
The whole router
I put the router in its own function, separate from main. It makes main shorter, and in part 14 the tests will call app() directly without starting a real server:
fn app() -> Router {
Router::new()
.route("/", get(root))
.route("/health", get(health))
.route("/links", get(list_links).post(create_link))
.route("/links/{id}", get(get_link))
.fallback(not_found)
}
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app()).await.unwrap();
}
Five routes, a fallback and the server, and the whole file is just over a hundred lines including the types and sample data.
Some numbers, for comparison with what you might be used to. A release build of this server (cargo build --release) is a single 2.1 MB file, with no runtime to install. Started and idle, it used about 3 MB of memory. A fresh Node process with Express is usually somewhere in the tens of megabytes before it handles a request. These numbers don't matter much on one server, but they add up when you run many small services, or pay for memory by the megabyte.
Extractor rules
Two rules about extractors will save you some confusion.
Every argument must be an extractor. You can't add a plain u32 and expect Axum to know where to get it:
#[debug_handler]
async fn hello(times: u32, name: String) -> String {
name.repeat(times as usize)
}
error[E0277]: the trait bound `u32: FromRequestParts<()>` is not satisfied
--> src/bin/e_debug2.rs:4:23
|
4 | async fn hello(times: u32, name: String) -> String {
| ^^^ the trait `FromRequestParts<()>` is not implemented for `u32`
|
= note: Function argument is not a valid axum extractor.
Where would the number come from? The path, the query, a header? You have to say, by wrapping it in an extractor like Path<u32> or Query<Params>.
Interestingly, String on its own is an extractor: it reads the whole request body as text. That brings up the second rule. The body can only be read once, so an extractor that consumes it must be the last argument:
#[debug_handler]
async fn update(Json(body): Json<serde_json::Value>, Path(id): Path<u64>) -> String {
format!("{id}: {body}")
}
error: `Json<_>` consumes the request body and thus must be the last argument to the handler function
--> src/bin/e_order.rs:4:29
|
4 | async fn update(Json(body): Json<serde_json::Value>, Path(id): Path<u64>) -> String {
| ^^^^
Swap them, and it compiles. Path, query, headers and state can come in any order, and the body comes last. In Axum's terms, the first kind implement FromRequestParts, which only looks at the request's head, and the body kind implement FromRequest, which takes the whole thing.
Serde in a little more depth
Real APIs need more control over JSON than the defaults give you. Here are the serde attributes I use most, with the output from a test program:
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
user_id: u64,
display_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
avatar_url: Option<String>,
bio: Option<String>,
#[serde(rename = "type")]
kind: Kind,
#[serde(skip)]
password_hash: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Kind {
Free,
Pro,
}
Serialising a profile with avatar_url and bio both None:
{
"userId": 7,
"displayName": "Ana",
"bio": null,
"type": "pro"
}
What each attribute did:
rename_all = "camelCase"turned the Rust field names, which aresnake_caseby convention, into thecamelCasethat JavaScript clients expect. One line, and both sides keep their own conventions.skip_serializing_if = "Option::is_none"leftavatarUrlout entirely. Without it, aNonebecomesnull, asbioshows.rename = "type"lets the JSON usetype, which is a keyword in Rust and can't be a field name.skipkeptpassword_hashout of the JSON completely. When deserialising, it's filled with the default value, an empty string. Having this on the type, rather than remembering to delete the field before every response, is how you avoid leaking it by accident.- On the enum,
rename_all = "lowercase"turned the variants into"free"and"pro".
Deserialising is strict about types and values:
invalid type: string "8", expected u64 at line 1 column 14
unknown variant `gold`, expected `free` or `pro` at line 1 column 49
But by default, it ignores fields it doesn't know about. My test input had an "extra": true that was silently dropped. That's usually what you want for an API, so old servers don't break when clients send new fields. If you'd rather reject them, #[serde(deny_unknown_fields)] on the struct does that:
unknown field `admin`, expected `name` at line 1 column 21
Express and Axum side by side
| Express | Axum |
|---|---|
const app = express() |
let app = Router::new() |
app.get("/path", handler) |
.route("/path", get(handler)) |
app.route("/x").get(a).post(b) |
.route("/x", get(a).post(b)) |
/links/:id |
/links/{id} |
req.params.id (always a string) |
Path(id): Path<u64> (parsed, or 400) |
req.query.limit (string or missing) |
Query(p): Query<Params> (typed struct) |
express.json() then req.body |
Json(input): Json<NewLink> (parsed and shaped, or 4xx) |
res.json(value) |
Return Json(value) |
res.status(201).json(value) |
Return (StatusCode::CREATED, Json(value)) |
res.sendStatus(404) |
Return StatusCode::NOT_FOUND |
app.use((req, res) => res.status(404)...) |
.fallback(handler) |
app.listen(3000) |
axum::serve(listener, app) |
| Mistakes show up at runtime | Many mistakes show up at compile time |
Exercises
- Add a
GET /tagsroute that returns every distinct tag across all links, sorted, as a JSON array. (ABTreeSetfrom part 8 does the sorting for you.) - Add an
offsetquery parameter to/linksthat skips that many links before applyinglimit, with a default of 0. Which iterator method do you need? - Add a
GET /links/{id}/tags/{tag}route that returnstrueorfalsedepending on whether the link has that tag. How do you extract two path parameters? (Hint:Path<(u64, String)>.) - Add
#[serde(rename_all = "camelCase")]toLinkand acreated_by: Stringfield. Check the JSON output with curl. - Write a handler that takes
headers: axum::http::HeaderMapand returns the value of theuser-agentheader, or"unknown". Where can aHeaderMapargument go in the argument list?
Next up: state, middleware and error responses
linkbox can answer requests, but it can't remember anything. Creating a link returns id 4 every time, and the link disappears as soon as the response is sent.
In part 11 we'll give the app shared state, so handlers can store and update links in memory using the Arc and lock patterns from part 9. We'll add middleware from tower-http for logging, timeouts and compression. And we'll replace the plain text error messages with an AppError type that turns every failure into a consistent JSON response, which is where thiserror from part 5 and the IntoResponse trait come together.