So far our Rust programs have only talked to the terminal. The terminal is a great listener. Never interrupts. Never asks for JSON. Frankly, it's the best relationship your code has ever had.
Time to put it on the internet anyway. [Cut to a tiny Rust crab in a suit at a speed-dating table, across from a web browser. The browser leans in. "So... what's your content type?" The crab sweats.]
Today we build a JSON API with Axum, the web framework from the Tokio team. It's a little notes service with a list, a create and a get-by-id, in about 50 lines. If you did the Tokio echo server, you already know half of it.
Set up
cargo new notes-api
cd notes-api
cargo add axum
cargo add tokio --features full
cargo add serde --features derive
Axum handles the routing, Tokio runs everything (it's our waiter from last time), and serde turns Rust structs into JSON and back.
The whole API
src/main.rs:
use axum::{
extract::{Path, State},
http::StatusCode,
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
#[derive(Clone, Serialize)]
struct Note {
id: u64,
text: String,
}
#[derive(Deserialize)]
struct NewNote {
text: String,
}
#[derive(Clone, Default)]
struct AppState {
notes: Arc<Mutex<Vec<Note>>>,
}
async fn list(State(state): State<AppState>) -> Json<Vec<Note>> {
Json(state.notes.lock().unwrap().clone())
}
async fn create(
State(state): State<AppState>,
Json(body): Json<NewNote>,
) -> (StatusCode, Json<Note>) {
let mut notes = state.notes.lock().unwrap();
let note = Note { id: notes.len() as u64 + 1, text: body.text };
notes.push(note.clone());
(StatusCode::CREATED, Json(note))
}
async fn get_one(
State(state): State<AppState>,
Path(id): Path<u64>,
) -> Result<Json<Note>, StatusCode> {
let notes = state.notes.lock().unwrap();
notes
.iter()
.find(|n| n.id == id)
.cloned()
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/notes", get(list).post(create))
.route("/notes/{id}", get(get_one))
.with_state(AppState::default());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
println!("listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
cargo run, then talk to it from another terminal:
curl -s -X POST localhost:3000/notes \
-H 'content-type: application/json' \
-d '{"text":"buy milk (check the expiry date)"}'
curl -s localhost:3000/notes
curl -s -i localhost:3000/notes/1
curl -s -i localhost:3000/notes/99
The first returns your note with "id":1 and a 201 Created. The list shows it. /notes/1 finds it, and /notes/99 gets a clean 404 Not Found. The crab got a second date.
How Axum thinks: handlers and extractors
Routes map a path and method to a function. get(list).post(create) puts two methods on the same path. {id} in a path is a placeholder (that's the syntax in current Axum; older tutorials use :id).
Handlers are plain async functions. No traits to implement, no macros on the function. Axum works out how to call them from their arguments.
Extractors are those arguments. Each one pulls something out of the request:
State(state)gets your shared app state.Path(id)reads{id}from the URL and parses it as au64. Ask for/notes/bananaand Axum rejects it with a 400 before your code ever runs. The banana is turned away at the door. (Some fruit just can't catch a break on this blog.)Json(body)reads the request body as JSON intoNewNote. A missing field or the wrong content type gets an error response automatically. One rule: the body extractor must be the last argument, because it consumes the request.
Return types become responses. Json<T> is a 200 with JSON. A tuple (StatusCode, Json<T>) sets the status. Result<Json<T>, StatusCode> means "this, or that error code", and ? works in handlers just like in the error-handling post.
About that Arc<Mutex<...>>
Many requests can run at the same time, on several threads, and they all want the notes list. Arc lets them share it safely, and Mutex makes sure only one changes it at a time. That's the "many readers or one writer" borrowing rule from the ownership post, enforced at run time across threads.
It's fine for a lab. In a real service the notes would live in a database. (See this blog's ORM showdown for SeaORM, which pairs nicely with Axum.) And never hold a std::sync::Mutex lock across an .await. Lock, do the quick thing and let go, the way these handlers do.
Homework
- Add
DELETE /notes/{id}that returns 204 No Content, or 404 if the note doesn't exist. - Reject empty notes: return
(StatusCode::UNPROCESSABLE_ENTITY, "text can't be empty")whenbody.text.trim()is empty. - Add logging with the
tower-httpcrate'sTraceLayerandtracing-subscriber, and watch every request fly by.
Your Rust code has a web address now. It grows up so fast. 馃
Cloud
More like this
Cloud
Ollama Review: Running Local LLMs on Your Own Machine, No Cloud Required
What if your AI assistant lived in your basement instead of someone else's data centre? A review of Ollama: how to run local LLMs with it, what hardware you really need, the API that makes it useful, and where it falls short.
Cloud
Async Rust With Tokio: Build an Echo Server That Juggles a Thousand Clients
One waiter, forty tables, and nobody waits for their soup. That's async. Learn async Rust with Tokio by building a 30-line TCP echo server, then meet the one mistake that freezes the whole restaurant.
Cloud
Rust Iterators: Fire Your for Loops (They'll Be Fine, They Have Savings)
Your for loop has been doing three jobs at once and it's tired. Rust iterators split the work into map, filter and sum, cost nothing extra at run time, and are lazier than a cat in a sunbeam. A ten-minute lab.