MARY.WIN

RUSTY — LARAVEL TO RUST — 15

Build a Laravel-style
application in Rust

A runnable local JSON application with validation, shared state, and HTTP tests.
Tutorial 15 of 16 in From Laravel to Rust. Before you start: Tutorials 1–14.

What happens between a JSON task request and the next task listing? In examples/src/bin/ep15.rs, Axum routes POST /tasks to create(). The handler validates the title before inserting a task. GET /tasks reads the stored tasks through list().

The first useful outcome is a normalized task visible in the next response. Store keeps tasks in memory, so restarting the process clears them. The task record contains an ID and title. This registry accepts and lists those records; executing commands, authentication, and persistent delivery require additional behavior.

Follow the request through four named boundaries: the route in app(), the Json<CreateTask> extractor, the title checks in create(), and the Store.tasks insertion. Then compare the successful request with blank, overlong, and malformed input.

This lesson follows one HTTP request from end to end in Axum, through four named boundaries: the route in app(), the Json<CreateTask> extractor, the title checks in create(), and the insertion into Store.tasks. Then it compares that request with blank, overlong, and malformed input, and reads the three tests that go through the router. It is the longer build; work in three passes: route and state, insertion and validation, then tests. It leaves out databases, authentication, queues, and running commands. The registry accepts and lists task records, each an ID and a title, and Store keeps them in memory, so a restart clears them. It assumes Tutorials 1 to 14.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep15.rs)

use axum::{extract::State, http::StatusCode, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, sync::{Arc, Mutex}};

#[derive(Clone, Debug, Deserialize, Serialize)]
struct Task { id: u64, title: String }

#[derive(Default)]
struct Store { next: u64, tasks: BTreeMap<u64, Task> }
type Shared = Arc<Mutex<Store>>;

#[derive(Deserialize)]
struct CreateTask { title: String }

async fn list(State(state): State<Shared>)
    -> Result<Json<Vec<Task>>, StatusCode>
{
    let store = state.lock().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(Json(store.tasks.values().cloned().collect()))
}

async fn create(State(state): State<Shared>, Json(input): Json<CreateTask>)
    -> Result<(StatusCode, Json<Task>), (StatusCode, &'static str)>
{
    let title = input.title.trim();
    if title.is_empty() || title.chars().count() > 80 {
        return Err((StatusCode::UNPROCESSABLE_ENTITY,
                    "title must contain 1 to 80 characters"));
    }
    let mut store = state.lock()
        .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "state unavailable"))?;
    let id = store.next.checked_add(1)
        .ok_or((StatusCode::SERVICE_UNAVAILABLE, "identifier space exhausted"))?;
    let task = Task { id, title: title.to_owned() };
    store.tasks.insert(id, task.clone());
    store.next = id;
    Ok((StatusCode::CREATED, Json(task)))
}

fn app() -> Router {
    let state = Arc::new(Mutex::new(Store::default()));
    Router::new().route("/tasks", get(list).post(create)).with_state(state)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    println!("task registry: http://127.0.0.1:3000/tasks");
    axum::serve(listener, app()).with_graceful_shutdown(async {
        let _ = tokio::signal::ctrl_c().await;
    }).await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{body::{to_bytes, Body}, http::Request};
    use tower::ServiceExt;

    fn post(body: &str) -> Request<Body> {
        Request::builder().method("POST").uri("/tasks")
            .header("content-type", "application/json")
            .body(Body::from(body.to_owned())).unwrap()
    }

    #[tokio::test]
    async fn creates_then_lists_the_normalized_record() {
        let app = app();
        let response = app.clone().oneshot(post(r#"{"title":" tests "}"#))
            .await.unwrap();
        assert_eq!(response.status(), StatusCode::CREATED);
        let response = app.oneshot(Request::builder().uri("/tasks")
            .body(Body::empty()).unwrap()).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = to_bytes(response.into_body(), 4096).await.unwrap();
        let tasks: Vec<Task> = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].id, 1);
        assert_eq!(tasks[0].title, "tests");
    }

    #[tokio::test]
    async fn rejects_blank_and_overlong_titles_without_inserting() {
        let app = app();
        for title in [" ".to_owned(), "x".repeat(81)] {
            let json = serde_json::json!({"title": title}).to_string();
            let response = app.clone().oneshot(post(&json)).await.unwrap();
            assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        }
        let response = app.oneshot(Request::builder().uri("/tasks")
            .body(Body::empty()).unwrap()).await.unwrap();
        let bytes = to_bytes(response.into_body(), 4096).await.unwrap();
        let tasks: Vec<Task> = serde_json::from_slice(&bytes).unwrap();
        assert!(tasks.is_empty());
    }

    #[tokio::test]
    async fn rejects_malformed_json() {
        let response = app().oneshot(post("{")).await.unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }
}

If it is too much on first read, skip to the walk-through below and come back. Use the companion package's Cargo.toml, which brings in Axum 0.8.9, Tokio, Serde, and Tower's test utilities, and keep its lockfile:

[package]
name = "laravel-to-rust-lessons"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
tokio = { version = "1", features = ["full"] }
axum = "=0.8.9"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tower = { version = "0.5", features = ["util"] }

Expected output from the tests, and when the server starts:

TERMINAL
cargo test --bin ep15
running 3 tests
test tests::creates_then_lists_the_normalized_record ... ok
test tests::rejects_malformed_json ... ok
test tests::rejects_blank_and_overlong_titles_without_inserting ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
TERMINAL
cargo run --locked --bin ep15
task registry: http://127.0.0.1:3000/tasks

The store that forgot

The Store kept every accepted task in a BTreeMap and regarded them as kept. It issued ID 1 to a task titled “Run tests” and returned it on request, in key order, like a drawer that gives back exactly what was put in it. The server was stopped with Ctrl-C and started again. GET /tasks returned [].

TERMINAL
curl -i -X POST http://127.0.0.1:3000/tasks \
  -H 'content-type: application/json' \
  -d '{"title":" Run tests "}'
HTTP/1.1 201 Created
content-type: application/json
content-length: 28

{"id":1,"title":"Run tests"}
TERMINAL
curl http://127.0.0.1:3000/tasks
[{"id":1,"title":"Run tests"}]

After the restart:

TERMINAL
curl http://127.0.0.1:3000/tasks
[]

Sometimes you want to see ownership, failure types, and shared state survive a real request before any database is involved. Take another look at Example 1 and follow one POST through its four boundaries, in the order the request meets them.

The route comes first. app() connects GET /tasks to list() and POST /tasks to create(), and State(state) gives each handler the shared store.

Then the extractor. Json(input) parses the body into CreateTask. It consumes the body, so it comes last in the signature, and malformed JSON is rejected before the title checks in create() run.

Then the title checks. create() calls input.title.trim() to remove surrounding whitespace, then rejects an empty result or one longer than 80 Unicode scalar values, which is what title.chars().count() counts.¹ A rejection returns HTTP 422 with title must contain 1 to 80 characters. Blank or overlong input returns here, before an ID is allocated or anything is inserted.

Then the insertion. Only after validation does state.lock() acquire the Store. checked_add(1) computes the next ID, or returns an availability error on overflow. store.tasks.insert(id, task.clone()) stores a snapshot, updating store.next records the allocated ID, and the handler returns HTTP 201 with its own task. That critical section contains no .await.

Three details follow from those lines. The store and the response each own a Task, so task.clone() makes the stored copy, and in list(), .values().cloned().collect() builds an owned response vector; serializing a response works on snapshots after the mutex guard can be released. Store.tasks is a BTreeMap<u64, Task>, so values() lists records in key order. And the first accepted task receives ID 1 because Store::default() starts next at zero.

How does this map to Laravel?

The router resembles a route declaration. Extractors cover parts of request conversion and validation, and are not a one-to-one Form Request equivalent. The handler performs the application operation. State assembly plays the role of wiring dependencies. Serde handles the JSON representation.

There is no Eloquent model here because there is no database, and no queue worker because a title registry is not a task executor.

What do the tests establish?

Take the three tests in order. creates_then_lists_the_normalized_record posts {"title":" tests "} through the router and expects HTTP 201, then sends a GET to the same app and expects one task, with ID 1 and title tests. rejects_blank_and_overlong_titles_without_inserting posts a blank title and an 81-character one, expects HTTP 422 for each, and then expects an empty listing. rejects_malformed_json sends { and expects HTTP 400.

These tests run the router in process, and they are, for all three green lines and for however much the request they build looks like the one a browser would send, evidence about the router and the handlers and nothing further out, so whether a deployed port is reachable, whether TLS works, and whether a client on another machine can connect are questions the test run did not ask.

The companion package also ran a socket check against the loopback address, and records its result separately. Its create and list requests returned the normalized record, its blank and 81-character titles each got HTTP 422, its { got HTTP 400, and the server exited with status 0 after an interrupt.

So the application answers requests and its tests pass. Now suppose the next requirement is that tasks survive a restart. Would you rename Store to Database? What would have to be true before you called the requirement met? Who would check it, and how?

Testing

Start from memory. Write the stages of the successful request in order: extract the JSON, normalize the title, validate its length, allocate the ID, insert the task, and return HTTP 201. Then match each stage to the test that observes it.

Then add a fetch-by-ID route. Before you write the handler, decide what the response for an absent ID should be. Predict the responses for a valid ID that is not in the store and for malformed path input, and write them down before you write the router tests.

Now compare. An absent task should get a not-found status, and malformed path input should keep the framework's own rejection. Test both through the router, and keep the mutex-protected work short.

Persistence needs a separate acceptance check, written before any implementation: create a task, stop the process, restart against the same storage, and retrieve that task. The restart in “The store that forgot” is the current in-memory Store failing that check.

TL;DR

The successful request goes: extract the JSON, normalize the title, validate its length, allocate the ID, insert the task, and return HTTP 201. Validation happens before the lock, and the lock covers one short insertion with no .await. The response owns its data. Three router tests observe creation, rejection, and malformed input, and say nothing about deployment. A restart clears Store, and persistence remains a separate acceptance criterion.

¹ Unicode scalar values are not always the same as user-perceived characters. In the companion package's socket check, a title of 80 scalar values was accepted with HTTP 201 and one of 81 was rejected with HTTP 422.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Axum 0.8.9 routing, State, Json, serve, and testing APIs; Tokio runtime and signal APIs; Serde derives; Rust standard-library Mutex and BTreeMap. The application and tests are original. This is a local teaching service, not a production deployment recipe.

NOT CHECKED — 4
  • The curl session, its response headers and the server's start-up line were observed on rustc 1.97.0 when this tutorial was first built. The recorded socket check on rustc 1.100.0 used the title "socket test" and records statuses and record counts, not this session's text.
  • The fetch-by-ID and persistence exercises were not written or run.
  • The comparisons between Axum routing, extractors and state and Laravel routes, Form Requests and dependency wiring are carried from the tutorial text and were not re-checked against the Laravel documentation for this edition.
  • The reference links were not opened for this edition.