Build a Tiny JSON API With Axum: Rust on the Web in Fifteen Minutes

Your Rust programs have been talking to the terminal. Time they talked to the internet. Build a notes API with Axum, with routes, JSON in and out, shared state and proper 404s, in about 50 lines.

Ada Brackett

4 min read

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

Bash
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:

Rust
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:

Bash
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 a u64. Ask for /notes/banana and 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 into NewNote. 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") when body.text.trim() is empty.
  • Add logging with the tower-http crate's TraceLayer and tracing-subscriber, and watch every request fly by.

Your Rust code has a web address now. It grows up so fast. 馃