Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
RECIPE 02 / 8

A small API with real contracts.

Create, list, complete, and delete tasks through a typed JSON API.

BY NAVAN SAMI~25 MIN BUILDLOCAL PROJECT
Download this project ↓
Axum 0.8Tokio 1Serde 1Tower 0.5

01 The shape of the build

A useful API separates transport input from valid domain state. This project normalizes titles, bounds the in-memory task count, uses stable IDs, and returns explicit HTTP status codes. A short synchronous mutex guard protects each tiny state operation and is never held across await. Storage is deliberately in memory: restarting clears the tasks. Tests call the router directly, while curl exercises the full network boundary.

  1. 1

    Deserialize a Create request and validate its trimmed title.

  2. 2

    Keep tasks in a BTreeMap for deterministic ID ordering.

  3. 3

    Return 201 for creation, 404 for unknown IDs, and 422 for invalid titles.

  4. 4

    Use a 4 KiB request-body limit and a 1,000-task capacity.

  5. 5

    Exercise both router tests and real HTTP requests.

02 Get it running

Install Rust stable and extract this project’s ZIP. Run these commands from the extracted task-api folder. The full workbench keeps it under cookbook/task-api.

terminal
cargo test
cargo run
# In another terminal:
curl -i -X POST http://127.0.0.1:3001/tasks -H "Content-Type: application/json" -d '{"title":"Build something"}'
curl http://127.0.0.1:3001/tasks
curl -X POST http://127.0.0.1:3001/tasks/1/complete
curl -i -X DELETE http://127.0.0.1:3001/tasks/1
WHAT YOU SHOULD SEE

POST creates {"id":1,"title":"Build something","complete":false}. Completion changes complete to true. DELETE returns 204; an unknown task returns 404.

First builds download dependencies. The included Cargo.lock files record the versions resolved during authoring. Use --locked with Cargo commands when you want to enforce those resolutions.

03 The complete source

Every source file below is also in the download. Start with the manifest, then follow the Rust entry point and any UI or test files.

Cargo.toml12 lines +
Cargo.toml
[package]
name = "task-api"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal"] }
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
[workspace]
src/lib.rs142 lines +
src/lib.rs
use axum::{
    Json, Router,
    extract::{DefaultBodyLimit, Path, State},
    http::StatusCode,
    routing::{delete, get, post},
};
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    sync::{Arc, Mutex},
};
#[derive(Clone, Serialize)]
struct Task {
    id: u64,
    title: String,
    complete: bool,
}
#[derive(Default)]
struct Store {
    next: u64,
    tasks: BTreeMap<u64, Task>,
}
type Shared = Arc<Mutex<Store>>;
#[derive(Deserialize)]
struct Create {
    title: String,
}
type ApiError = (StatusCode, &'static str);
async fn list(State(state): State<Shared>) -> Result<Json<Vec<Task>>, ApiError> {
    let store = state
        .lock()
        .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "store unavailable"))?;
    Ok(Json(store.tasks.values().cloned().collect()))
}
async fn create(
    State(state): State<Shared>,
    Json(input): Json<Create>,
) -> Result<(StatusCode, Json<Task>), ApiError> {
    let title = input.title.trim();
    if title.is_empty() || title.chars().count() > 80 {
        return Err((
            StatusCode::UNPROCESSABLE_ENTITY,
            "title must contain 1–80 characters",
        ));
    }
    let mut store = state
        .lock()
        .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "store unavailable"))?;
    if store.tasks.len() >= 1000 {
        return Err((StatusCode::SERVICE_UNAVAILABLE, "practice store is full"));
    }
    store.next = store
        .next
        .checked_add(1)
        .ok_or((StatusCode::SERVICE_UNAVAILABLE, "ID space exhausted"))?;
    let task = Task {
        id: store.next,
        title: title.to_owned(),
        complete: false,
    };
    store.tasks.insert(task.id, task.clone());
    Ok((StatusCode::CREATED, Json(task)))
}
async fn complete(
    State(state): State<Shared>,
    Path(id): Path<u64>,
) -> Result<Json<Task>, ApiError> {
    let mut store = state
        .lock()
        .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "store unavailable"))?;
    let task = store
        .tasks
        .get_mut(&id)
        .ok_or((StatusCode::NOT_FOUND, "task not found"))?;
    task.complete = true;
    Ok(Json(task.clone()))
}
async fn remove(State(state): State<Shared>, Path(id): Path<u64>) -> Result<StatusCode, ApiError> {
    let mut store = state
        .lock()
        .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "store unavailable"))?;
    store
        .tasks
        .remove(&id)
        .ok_or((StatusCode::NOT_FOUND, "task not found"))?;
    Ok(StatusCode::NO_CONTENT)
}
pub fn app() -> Router {
    Router::new()
        .route("/tasks", get(list).post(create))
        .route("/tasks/{id}/complete", post(complete))
        .route("/tasks/{id}", delete(remove))
        .layer(DefaultBodyLimit::max(4096))
        .with_state(Shared::default())
}
#[cfg(test)]
mod tests {
    use super::*;
    use axum::{body::Body, http::Request};
    use tower::ServiceExt;
    async fn request(app: Router, method: &str, uri: &str, body: &str) -> StatusCode {
        app.oneshot(
            Request::builder()
                .method(method)
                .uri(uri)
                .header("content-type", "application/json")
                .body(Body::from(body.to_owned()))
                .unwrap(),
        )
        .await
        .unwrap()
        .status()
    }
    #[tokio::test]
    async fn contracts() {
        let router = app();
        assert_eq!(
            request(router.clone(), "POST", "/tasks", r#"{"title":"Build"}"#).await,
            StatusCode::CREATED
        );
        assert_eq!(
            request(router.clone(), "POST", "/tasks", r#"{"title":" "}"#).await,
            StatusCode::UNPROCESSABLE_ENTITY
        );
        assert_eq!(
            request(router.clone(), "POST", "/tasks/99/complete", "").await,
            StatusCode::NOT_FOUND
        );
        assert_eq!(
            request(router.clone(), "POST", "/tasks/1/complete", "").await,
            StatusCode::OK
        );
        assert_eq!(
            request(router.clone(), "DELETE", "/tasks/1", "").await,
            StatusCode::NO_CONTENT
        );
        assert_eq!(
            request(router, "DELETE", "/tasks/1", "").await,
            StatusCode::NOT_FOUND
        );
    }
}
src/main.rs11 lines +
src/main.rs
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3001").await?;
    println!("Task API: http://127.0.0.1:3001/tasks");
    axum::serve(listener, task_api::app())
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}

04 Check the behavior

  • □cargo test checks creation, invalid titles, unknown completion, and deletion.
  • □Whitespace-only and over-80-scalar titles return 422.
  • □Restarting produces an empty list, matching the stated in-memory contract.

05 Know what you are building on

This is a single-process, in-memory example without users or authorization.

Mutex poisoning becomes HTTP 500; a production recovery policy depends on the protected invariant.

Use a persistent database and migrations before promising durable tasks.

MAKE IT YOUR OWN

Choose one boundary to improve. Write down the new behavior, add a test that demonstrates it, then change the implementation. Keep the original working path intact.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.