Build an inventory API
Quick answer
An inventory API combines a typed request contract, validation, storage and observable HTTP responses. Build the domain operation first, then connect it to a handler.
Reserve stock without violating invariants
A reservation must be positive and cannot exceed available stock. Check the rules before mutating state. The first example isolates domain logic; the second uses a disposable single-process in-memory store shared by an Axum handler. Use the existing Axum, Tokio, Tower and serde candidates; the handler uses a standard Mutex only for a short synchronous operation and holds no lock across await. For a database-backed service use a conditional update in a transaction and check affected rows. A real authenticated inventory service must enforce authorization, request size, idempotency and persistence; this is only a local learning prototype.
fn reserve(stock: &mut u32, n: u32) -> Result<(), &'static str> { if n == 0 || n > *stock { return Err("invalid reservation"); } *stock -= n; Ok(())}fn main() { let mut stock = 5; println!("{}", reserve(&mut stock, 3).is_ok()); println!("{}", reserve(&mut stock, 4).is_ok()); println!("{stock}");}Expected stdout (not executed):
truefalse2The failed second reservation leaves two units available.
use axum::{Router, Json, extract::State, routing::post, body::Body, http::{Request, StatusCode}};use serde::Deserialize;use std::sync::{Arc, Mutex};use tower::ServiceExt;#[derive(Deserialize)]struct Reservation { quantity: u32 }async fn reserve(State(stock): State<Arc<Mutex<u32>>>, Json(r): Json<Reservation>) -> StatusCode { let Ok(mut n) = stock.lock() else { return StatusCode::INTERNAL_SERVER_ERROR; }; if r.quantity == 0 { return StatusCode::BAD_REQUEST; } if r.quantity > *n { return StatusCode::CONFLICT; } *n -= r.quantity; StatusCode::NO_CONTENT}#[tokio::main(flavor = "current_thread")]async fn main() { let stock = Arc::new(Mutex::new(5)); let app = Router::new().route("/reserve", post(reserve)).with_state(stock.clone()); for q in [3, 4] { let req = Request::builder().method("POST").uri("/reserve").header("content-type", "application/json").body(Body::from(format!("{{\"quantity\":{q}}}"))).unwrap(); println!("{}", app.clone().oneshot(req).await.unwrap().status().as_u16()); } println!("{}", *stock.lock().unwrap());}Manual local Rust/Cargo candidate; not executed. Expected behavior:
2044092The in-process service test checks the response and shared state.
Common mistake
Do not expose this unauthenticated prototype to real clients or treat an in-memory lock as a distributed transaction.
Try it yourself
Add tests for zero, malformed JSON and an exact-stock reservation, then outline a transactional SQLite replacement.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Build an inventory API — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A stock reservation is rejected for insufficient inventory. What invariant must a follow-up read confirm?
Build an inventory API — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn reserve(stock: &mut u32, n: u32) -> Result<(), &'static str> { if n == 0 || n > *stock { return Err("invalid reservation"); } *stock -= n; Ok(()) } fn main() { let mut stock = 5; println!("{}", reserve(&mut stock, 3).is_ok()); println!("{}", reserve(&mut stock, 4).is_ok()); println!("{stock}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Build an inventory API — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use axum::{Router, Json, extract::State, routing::post, body::Body, http::{Request, StatusCode}}; use serde::Deserialize; use std::sync::{Arc, Mutex}; use tower::ServiceExt; #[derive(Deserialize)] struct Reservation { quantity: u32 } async fn reserve(State(stock): State<Arc<Mutex<u32>>>, Json(r): Json<Reservation>) -> StatusCode { let Ok(mut n) = stock.lock() else { return StatusCode::INTERNAL_SERVER_ERROR; }; if r.quantity == 0 { return StatusCode::BAD_REQUEST; } if r.quantity > *n { return StatusCode::CONFLICT; } *n -= r.quantity; StatusCode::NO_CONTENT } #[tokio::main(flavor = "current_thread")] async fn main() { let stock = Arc::new(Mutex::new(5)); let app = Router::new().route("/reserve", post(reserve)).with_state(stock.clone()); for q in [3, 4] { let req = Request::builder().method("POST").uri("/reserve").header("content-type", "application/json").body(Body::from(format!("{{\"quantity\":{q}}}"))).unwrap(); println!("{}", app.clone().oneshot(req).await.unwrap().status().as_u16()); } println!("{}", *stock.lock().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.