Skip to content

Lesson 58 of 59Production

Project: A Warehouse Stock API

Build a small warehouse stock service with FastAPI on your own machine, stage by stage: a uv project, SQLAlchemy 2 models, Pydantic schemas with Problem Details errors, stock movements that can never go negative, idempotency keys for safe retries, and a pytest suite.

14 min read0/4 questions

You have built routes, models, dependencies and tests one lesson at a time. This project puts them in one service, in the order a backend developer really adds them. The app is the stock API behind a small warehouse. Pickers scan items out, the loading dock scans deliveries in, and the API keeps a count per item. The count must never go below zero, and a handheld scanner on bad Wi-Fi must be able to retry without counting a box twice.

FastAPI needs a real Python process and a real server, so this is a guided build. You type the files on your own machine, run the exact commands, and compare your output with the output shown. Three pieces of pure logic do run here in the browser: the validation rules, the stock update and the idempotency check. They use only the standard library and sqlite3, so you can poke at the hard parts before you wire them in.

Version numbers move fast. The code below was checked with FastAPI 0.161, SQLAlchemy 2.1, Pydantic 2 and Python 3.13. If something behaves differently on your machine, the FastAPI and SQLAlchemy docs are the reference, not this page.

The plan: one rule per layer

The service has four layers, as in Structuring a FastAPI Project. Routes speak HTTP and nothing else. Schemas check what comes in. A service module holds the stock rules and owns the transaction. The database enforces what must always be true, even if the code has a bug.

One stock movement, layer by layer
Scanner: POST + Idempotency-KeyScannerPOST + Idempotency-Keyroutes.py: HTTP onlyroutes.pyHTTP onlyschemas.py: 422 on bad inputschemas.py422 on bad inputstock.py: rules + commitstock.pyrules + commitSQLite / Postgres: CHECK on_hand >= 0SQLite / PostgresCHECK on_hand >= 0errors.py: Problem Detailserrors.pyProblem DetailsJSONvalidateMovementCreateone transactiondomain errorproblem+json

The scanner sends a movement and a key it generated once for this scan.

1/4

Stage 1: a uv project that runs

Start the way uv for Real Projects taught: one tool for the Python version, the virtual environment and the lockfile.

uv init stockroomcd stockroomuv add "fastapi[standard]" sqlalchemy pydantic-settingsuv add --dev pytest ruff httpx2

uv init prints a line that starts with Initialized project, and each uv add updates pyproject.toml and uv.lock. httpx2 is there for the test client. As Testing FastAPI explained, current Starlette looks for httpx2 first and warns if it only finds httpx. The httpx packages are in transition, so check the Starlette release notes if that warning still shows up.

Delete the main.py that uv init made, and create the package folders:

rm main.pymkdir app teststouch app/__init__.py tests/__init__.py

Add a Ruff section to the end of pyproject.toml, as in Code Quality Tools. A line length of 100 keeps the code below readable:

pyproject.toml (add at the end)
[tool.ruff]
line-length = 100

Then the smallest app that proves the setup works, from Your First FastAPI App:

app/main.py
from fastapi import FastAPI
 
app = FastAPI(title="Stockroom")
 
 
@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}
uv run fastapi dev app/main.py

You should see a banner that ends with Server started at http://127.0.0.1:8000 and Documentation at http://127.0.0.1:8000/docs. In a second terminal:

curl -s http://127.0.0.1:8000/health
{"status":"ok"}

Check: /health answers, /docs shows one route, and uv run ruff check . prints All checks passed!. Leave the dev server running. It reloads when you save a file.

Stage 2: settings, a session and the models

Next comes storage, from Settings and Config and Databases with SQLAlchemy. The database URL comes from the environment, with a SQLite file as the default so you need no server today. Set STOCKROOM_DATABASE_URL to a Postgres URL later and nothing else changes.

app/settings.py
from pydantic_settings import BaseSettings, SettingsConfigDict
 
 
class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env", env_prefix="STOCKROOM_")
 
    database_url: str = "sqlite:///./stockroom.db"
 
 
settings = Settings()

The session comes from a yield dependency, as in Dependency Injection. Read the comment on yield. Since FastAPI 0.118, the code after yield runs after the response has been sent. If this dependency committed there and the commit failed, the scanner would already have its 201 for a movement that never saved. So the dependency only opens and closes the session, and the service commits before it returns.

app/db.py
from collections.abc import Iterator
from typing import Annotated
 
from fastapi import Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
 
from app.settings import settings
 
engine = create_engine(settings.database_url)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
 
 
class Base(DeclarativeBase):
    pass
 
 
def get_db() -> Iterator[Session]:
    with SessionLocal() as db:
        yield db  # the service commits; this only closes the session
 
 
DB = Annotated[Session, Depends(get_db)]

The models use the SQLAlchemy 2 style: Mapped[...] type hints and mapped_column. Two choices matter. The CheckConstraint makes a negative count impossible at the database level, whatever the Python code does. And Movement stores every change with the count after it, so you can always explain how a number got where it is.

app/models.py
from datetime import UTC, datetime
 
from sqlalchemy import CheckConstraint, ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column
 
from app.db import Base
 
 
class Item(Base):
    __tablename__ = "items"
    __table_args__ = (CheckConstraint("on_hand >= 0", name="on_hand_not_negative"),)
 
    id: Mapped[int] = mapped_column(primary_key=True)
    sku: Mapped[str] = mapped_column(String(8), unique=True)
    name: Mapped[str] = mapped_column(String(100))
    on_hand: Mapped[int] = mapped_column(default=0)
 
 
class Movement(Base):
    __tablename__ = "movements"
 
    id: Mapped[int] = mapped_column(primary_key=True)
    item_id: Mapped[int] = mapped_column(ForeignKey("items.id"))
    kind: Mapped[str] = mapped_column(String(10))
    quantity: Mapped[int]
    on_hand_after: Mapped[int]
    created_at: Mapped[datetime] = mapped_column(default=lambda: datetime.now(UTC))

Check: create the tables once and list them.

uv run python -c "from app.db import Base, engine; import app.models; Base.metadata.create_all(engine); print(sorted(Base.metadata.tables))"
['items', 'movements']

A stockroom.db file now exists. create_all is fine for a project like this, but it only creates missing tables and never alters existing ones. On a real team every schema change is an Alembic migration, as in Database Migrations with Alembic.

Stage 3: the contract and its errors

Now the shape of the API. Following Designing a CRUD API, items live at /items, one item at /items/{sku}, and its movements at /items/{sku}/movements. Input and output get separate models, from Pydantic Models, so internal fields like id never leak by accident.

app/schemas.py
from typing import Annotated, Literal
 
from pydantic import BaseModel, ConfigDict, Field
 
Sku = Annotated[str, Field(pattern=r"^[A-Z]{3}-\d{4}$", examples=["MUG-0001"])]
 
 
class ItemCreate(BaseModel):
    sku: Sku
    name: Annotated[str, Field(min_length=1, max_length=100)]
 
 
class ItemRead(BaseModel):
    model_config = ConfigDict(from_attributes=True)
 
    sku: str
    name: str
    on_hand: int
 
 
class MovementCreate(BaseModel):
    kind: Literal["receive", "pick"]
    quantity: Annotated[int, Field(gt=0, le=10_000)]
 
 
class MovementRead(BaseModel):
    id: int
    sku: str
    kind: str
    quantity: int
    on_hand_after: int

Pydantic does a lot of work in those few lines. Here are the same rules written by hand, so you can see exactly what it checks and what a client gets back. Run it, then add your own bad requests to the list.

Pythonvalidate_movement.py
import re SKU = re.compile(r"^[A-Z]{3}-\d{4}$") def check_movement(sku, body): """Return a list of errors in the same shape FastAPI uses for a 422.""" errors = [] if not SKU.fullmatch(sku): errors.append({"loc": ["path", "sku"], "msg": "should match AAA-0000"}) if not isinstance(body, dict): return errors + [{"loc": ["body"], "msg": "should be an object"}] if body.get("kind") not in ("receive", "pick"): errors.append({"loc": ["body", "kind"], "msg": "should be 'receive' or 'pick'"}) quantity = body.get("quantity") if type(quantity) is not int: errors.append({"loc": ["body", "quantity"], "msg": "should be a whole number"}) elif not 0 < quantity <= 10_000: errors.append({"loc": ["body", "quantity"], "msg": "should be from 1 to 10000"}) return errors requests = [ ("MUG-0001", {"kind": "receive", "quantity": 10}), ("MUG-0001", {"kind": "pick", "quantity": 0}), ("mug-1", {"kind": "steal", "quantity": "lots"}), ("MUG-0001", ["pick", 3]),]for sku, body in requests: errors = check_movement(sku, body) if errors: print(f"422 {sku}:", "; ".join(f"{'.'.join(e['loc'])} {e['msg']}" for e in errors)) else: print(f"ok {sku}: {body['kind']} {body['quantity']}")
Output
Press Run (⌘ Enter) to see what happens.

Notice that all the errors come back at once, each with a location. That is what makes a 422 useful to the client team.

Errors your own code raises need one shape too. Error Responses Clients Can Rely On showed RFC 9457 Problem Details. The service raises small domain exceptions that know nothing about HTTP routes, and one handler turns them into application/problem+json, the pattern from Errors and Middleware:

app/errors.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
 
 
class ProblemError(Exception):
    status = 400
    title = "Bad request"
 
    def __init__(self, detail: str) -> None:
        super().__init__(detail)
        self.detail = detail
 
 
class NotFound(ProblemError):
    status = 404
    title = "Not found"
 
 
class Conflict(ProblemError):
    status = 409
    title = "Conflict"
 
 
class OutOfStock(ProblemError):
    status = 409
    title = "Not enough stock"
 
 
async def problem_handler(request: Request, exc: Exception) -> JSONResponse:
    assert isinstance(exc, ProblemError)
    return JSONResponse(
        status_code=exc.status,
        media_type="application/problem+json",
        content={
            "type": "about:blank",
            "title": exc.title,
            "status": exc.status,
            "detail": exc.detail,
        },
    )
 
 
def install_handlers(app: FastAPI) -> None:
    app.add_exception_handler(ProblemError, problem_handler)

The service creates and reads items. A duplicate SKU hits the unique constraint, and the service turns that IntegrityError into a 409 instead of a 500:

app/stock.py
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
 
from app.errors import Conflict, NotFound
from app.models import Item
from app.schemas import ItemCreate
 
 
def create_item(db: Session, data: ItemCreate) -> Item:
    item = Item(sku=data.sku, name=data.name)
    db.add(item)
    try:
        db.commit()
    except IntegrityError:
        db.rollback()
        raise Conflict(f"SKU {data.sku} already exists") from None
    return item
 
 
def get_item(db: Session, sku: str) -> Item:
    item = db.scalar(select(Item).where(Item.sku == sku))
    if item is None:
        raise NotFound(f"No item with SKU {sku}")
    return item

The routes stay thin. They take the input, call the service and return its result, and the path type Sku gives you the 422 for free (Path and Query Parameters):

app/routes.py
from fastapi import APIRouter
 
from app import stock
from app.db import DB
from app.schemas import ItemCreate, ItemRead, Sku
 
router = APIRouter(prefix="/items", tags=["items"])
 
 
@router.post("", status_code=201, response_model=ItemRead)
def create_item(data: ItemCreate, db: DB):
    return stock.create_item(db, data)
 
 
@router.get("/{sku}", response_model=ItemRead)
def read_item(sku: Sku, db: DB):
    return stock.get_item(db, sku)

Replace app/main.py so it installs the handler, includes the router and creates tables at startup in a lifespan function:

app/main.py
from contextlib import asynccontextmanager
 
from fastapi import FastAPI
 
from app.db import Base, engine
from app.errors import install_handlers
from app.routes import router
 
 
@asynccontextmanager
async def lifespan(app: FastAPI):
    Base.metadata.create_all(engine)  # fine for a project; use Alembic for real schema changes
    yield
 
 
app = FastAPI(title="Stockroom", lifespan=lifespan)
install_handlers(app)
app.include_router(router)
 
 
@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}

Check: create a mug twice, then ask for an item that does not exist.

curl -s -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"sku": "MUG-0001", "name": "Blue mug"}'curl -s -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"sku": "MUG-0001", "name": "Blue mug"}'curl -s http://127.0.0.1:8000/items/NOP-0000
{"sku":"MUG-0001","name":"Blue mug","on_hand":0}
{"type":"about:blank","title":"Conflict","status":409,"detail":"SKU MUG-0001 already exists"}
{"type":"about:blank","title":"Not found","status":404,"detail":"No item with SKU NOP-0000"}

-SkipHttpErrorCheck needs PowerShell 7. You can also try every call from /docs, which now shows both schemas.

Match the pairs0/5 matched

Match each request to the status code this API returns.

Choose an item, then its match on the other side.

Stage 4: stock that never goes negative

This is the heart of the app, and the bug from Transactions and Concurrency Bugs in Web Apps. The obvious code reads the count, checks it in Python and writes the new number. Two pickers doing that at the same moment both see 6 mugs, both take 4, and the count says 2 while the shelf is empty.

The fix is to let the database check and change the row in one statement: UPDATE ... SET on_hand = on_hand - 4 WHERE on_hand - 4 >= 0. If no row matches, there was not enough stock. Try both versions here:

Pythonstock_update.py
import sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE items ( id INTEGER PRIMARY KEY, sku TEXT NOT NULL UNIQUE, on_hand INTEGER NOT NULL DEFAULT 0 CHECK (on_hand >= 0));CREATE TABLE movements ( id INTEGER PRIMARY KEY, item_id INTEGER NOT NULL REFERENCES items(id), kind TEXT NOT NULL, quantity INTEGER NOT NULL, on_hand_after INTEGER NOT NULL);INSERT INTO items (sku, on_hand) VALUES ('MUG-0001', 5);""") class OutOfStock(Exception): pass def record_movement(db, sku, kind, quantity): """One movement, one transaction. The UPDATE checks and changes stock in a single step.""" change = quantity if kind == "receive" else -quantity with db: # commits on success, rolls back on an exception row = db.execute( "UPDATE items SET on_hand = on_hand + ? " "WHERE sku = ? AND on_hand + ? >= 0 RETURNING id, on_hand", (change, sku, change), ).fetchone() if row is None: raise OutOfStock(f"cannot {kind} {quantity} of {sku}") item_id, on_hand_after = row db.execute( "INSERT INTO movements (item_id, kind, quantity, on_hand_after) VALUES (?, ?, ?, ?)", (item_id, kind, quantity, on_hand_after), ) return on_hand_after for kind, quantity in [("pick", 3), ("receive", 4), ("pick", 9)]: try: print(f"{kind:7} {quantity}: on hand {record_movement(db, 'MUG-0001', kind, quantity)}") except OutOfStock as e: print(f"{kind:7} {quantity}: 409, {e}") # The bug this avoids. Two pickers read stock first, then each writes "what I saw minus 4".seen_by_a = db.execute("SELECT on_hand FROM items").fetchone()[0]seen_by_b = db.execute("SELECT on_hand FROM items").fetchone()[0]with db: db.execute("UPDATE items SET on_hand = ?", (seen_by_a - 4,)) db.execute("UPDATE items SET on_hand = ?", (seen_by_b - 4,))print("read then write: 8 mugs picked, on hand", db.execute("SELECT on_hand FROM items").fetchone()[0]) with db: db.execute("UPDATE items SET on_hand = 6")for picker in ("A", "B"): try: print(f"picker {picker}: on hand {record_movement(db, 'MUG-0001', 'pick', 4)}") except OutOfStock as e: print(f"picker {picker}: 409, {e}")
Output
Press Run (⌘ Enter) to see what happens.

The read-then-write version lost an update: eight mugs left the shelf, but the count only fell by four. The conditional version gives the second picker a clear 409. In Postgres the second UPDATE waits for the first to commit, then rechecks the WHERE against the new value, so this holds under real concurrency too. The CHECK constraint is the backstop if someone ever writes the naive version.

Now the same statement in SQLAlchemy 2. Add record_movement to app/stock.py, and update its imports:

app/stock.py (imports)
from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
 
from app.errors import Conflict, NotFound, OutOfStock
from app.models import Item, Movement
from app.schemas import ItemCreate, MovementCreate, MovementRead
app/stock.py (add at the end)
def record_movement(db: Session, sku: str, data: MovementCreate) -> MovementRead:
    item = get_item(db, sku)
    change = data.quantity if data.kind == "receive" else -data.quantity
    stmt = (
        update(Item)
        .where(Item.id == item.id, Item.on_hand + change >= 0)
        .values(on_hand=Item.on_hand + change)
        .returning(Item.on_hand)
    )
    on_hand_after = db.execute(stmt).scalar_one_or_none()
    if on_hand_after is None:
        db.rollback()
        raise OutOfStock(f"Only {item.on_hand} of {sku} on hand, cannot pick {data.quantity}")
 
    movement = Movement(
        item_id=item.id, kind=data.kind, quantity=data.quantity, on_hand_after=on_hand_after
    )
    db.add(movement)
    db.commit()  # commit here, so a failure becomes an error response
    return MovementRead(
        id=movement.id, sku=sku, kind=data.kind, quantity=data.quantity, on_hand_after=on_hand_after
    )

And a route in app/routes.py. Add MovementCreate and MovementRead to its schema import:

app/routes.py (add at the end)
@router.post("/{sku}/movements", status_code=201, response_model=MovementRead)
def add_movement(sku: Sku, data: MovementCreate, db: DB):
    return stock.record_movement(db, sku, data)

RETURNING works on Postgres and on SQLite 3.35 and later, which current Python builds include. Check: receive 5, then try to pick 8.

curl -s -X POST http://127.0.0.1:8000/items/MUG-0001/movements -H "Content-Type: application/json" -d '{"kind": "receive", "quantity": 5}'curl -s -X POST http://127.0.0.1:8000/items/MUG-0001/movements -H "Content-Type: application/json" -d '{"kind": "pick", "quantity": 8}'
{"id":1,"sku":"MUG-0001","kind":"receive","quantity":5,"on_hand_after":5}
{"type":"about:blank","title":"Not enough stock","status":409,"detail":"Only 5 of MUG-0001 on hand, cannot pick 8"}
Quick check
A teammate moves db.commit() out of record_movement and into get_db, after the yield. On FastAPI 0.118 or later, what can go wrong?
Need a nudge? A hint rules out a wrong answer.

Stage 5: safe retries with idempotency keys

A scanner sends "received 10", the Wi-Fi drops before the 201 arrives, and the scanner retries. Without protection, the shelf now shows 20. Safe Retries with Idempotency Keys gave the fix. The client generates a key once per scan and sends it with every retry. The server stores the key, a fingerprint of the request and the response, in the same transaction as the stock change. A repeat with the same key and the same body gets the stored response. The same key with a different body is a client bug, and it gets a 422.

Here is the whole check with sqlite3. Run it and read each line:

Pythonidempotency.py
import hashlibimport jsonimport sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE items ( id INTEGER PRIMARY KEY, sku TEXT NOT NULL UNIQUE, on_hand INTEGER NOT NULL DEFAULT 0 CHECK (on_hand >= 0));CREATE TABLE movements ( id INTEGER PRIMARY KEY, item_id INTEGER NOT NULL REFERENCES items(id), kind TEXT NOT NULL, quantity INTEGER NOT NULL, on_hand_after INTEGER NOT NULL);CREATE TABLE idempotency_keys ( key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, response_body TEXT NOT NULL);INSERT INTO items (sku, on_hand) VALUES ('MUG-0001', 0);""") class Problem(Exception): def __init__(self, status, detail): super().__init__(detail) self.status = status def fingerprint(sku, body): canonical = json.dumps({"sku": sku, **body}, sort_keys=True) return hashlib.sha256(canonical.encode()).hexdigest() def find_replay(db, key, fp): row = db.execute( "SELECT fingerprint, response_body FROM idempotency_keys WHERE key = ?", (key,) ).fetchone() if row is None: return None if row[0] != fp: raise Problem(422, f"key {key} was first used for a different movement") return json.loads(row[1]) def record_movement(db, sku, body, key): fp = fingerprint(sku, body) replay = find_replay(db, key, fp) if replay is not None: return 201, replay, True change = body["quantity"] if body["kind"] == "receive" else -body["quantity"] with db: # stock, movement and key commit together, or not at all row = db.execute( "UPDATE items SET on_hand = on_hand + ? " "WHERE sku = ? AND on_hand + ? >= 0 RETURNING id, on_hand", (change, sku, change), ).fetchone() if row is None: raise Problem(409, "not enough stock") cur = db.execute( "INSERT INTO movements (item_id, kind, quantity, on_hand_after) VALUES (?, ?, ?, ?)", (row[0], body["kind"], body["quantity"], row[1]), ) result = {"id": cur.lastrowid, "sku": sku, **body, "on_hand_after": row[1]} db.execute( "INSERT INTO idempotency_keys VALUES (?, ?, ?)", (key, fp, json.dumps(result)) ) return 201, result, False calls = [ ("first try", {"kind": "receive", "quantity": 10}, "phone-7f3a"), ("retry after timeout", {"kind": "receive", "quantity": 10}, "phone-7f3a"), ("same fields, new order", {"quantity": 10, "kind": "receive"}, "phone-7f3a"), ("key reused, new body", {"kind": "receive", "quantity": 99}, "phone-7f3a"), ("a real second receive", {"kind": "receive", "quantity": 10}, "phone-91bc"), ("pick too many", {"kind": "pick", "quantity": 50}, "phone-c210"), ("retry the failed pick", {"kind": "pick", "quantity": 50}, "phone-c210"),]for label, body, key in calls: try: status, result, replayed = record_movement(db, "MUG-0001", body, key) note = " (replayed)" if replayed else "" print(f"{label:24} {status} movement {result['id']}, on hand {result['on_hand_after']}{note}") except Problem as e: print(f"{label:24} {e.status} {e}") print("on hand:", db.execute("SELECT on_hand FROM items").fetchone()[0])print("movements:", db.execute("SELECT COUNT(*) FROM movements").fetchone()[0])print("saved keys:", [r[0] for r in db.execute("SELECT key FROM idempotency_keys")])
Output
Press Run (⌘ Enter) to see what happens.

Two retries, one movement. Notice the failed pick: its key was never saved, because the error rolled back the whole transaction. Retrying it runs the check again, which is right, since stock may have arrived in between.

Predict the outputPython

What does this print?

import json

a = json.dumps({"kind": "pick", "quantity": 2}, sort_keys=True)
b = json.dumps({"quantity": 2, "kind": "pick"}, sort_keys=True)
c = json.dumps({"quantity": 2, "kind": "pick"})
print(a == b, a == c)
Need a nudge? Hints walk you through it.

Now the real version. Add the model to app/models.py. It is a new table, so create_all adds it when the server restarts:

app/models.py (add at the end)
class IdempotencyKey(Base):
    __tablename__ = "idempotency_keys"
 
    key: Mapped[str] = mapped_column(String(255), primary_key=True)
    fingerprint: Mapped[str] = mapped_column(String(64))
    response_body: Mapped[str]

Add the error to app/errors.py:

app/errors.py (add after OutOfStock)
class KeyReused(ProblemError):
    status = 422
    title = "Idempotency-Key reused with a different request"

Then replace record_movement in app/stock.py. The new imports are hashlib and json at the top, KeyReused from app.errors and IdempotencyKey from app.models.

app/stock.py (replace record_movement)
def fingerprint(sku: str, data: MovementCreate) -> str:
    canonical = json.dumps({"sku": sku, **data.model_dump()}, sort_keys=True)
    return hashlib.sha256(canonical.encode()).hexdigest()
 
 
def find_replay(db: Session, key: str, fp: str) -> MovementRead | None:
    saved = db.get(IdempotencyKey, key)
    if saved is None:
        return None
    if saved.fingerprint != fp:
        raise KeyReused(f"Key {key} was first used for a different movement")
    return MovementRead.model_validate_json(saved.response_body)
 
 
def record_movement(
    db: Session, sku: str, data: MovementCreate, key: str
) -> tuple[MovementRead, bool]:
    fp = fingerprint(sku, data)
    replay = find_replay(db, key, fp)
    if replay is not None:
        return replay, True
 
    item = get_item(db, sku)
    change = data.quantity if data.kind == "receive" else -data.quantity
    stmt = (
        update(Item)
        .where(Item.id == item.id, Item.on_hand + change >= 0)
        .values(on_hand=Item.on_hand + change)
        .returning(Item.on_hand)
    )
    on_hand_after = db.execute(stmt).scalar_one_or_none()
    if on_hand_after is None:
        db.rollback()
        raise OutOfStock(f"Only {item.on_hand} of {sku} on hand, cannot pick {data.quantity}")
 
    movement = Movement(
        item_id=item.id, kind=data.kind, quantity=data.quantity, on_hand_after=on_hand_after
    )
    db.add(movement)
    db.flush()  # assigns movement.id
    result = MovementRead(
        id=movement.id, sku=sku, kind=data.kind, quantity=data.quantity, on_hand_after=on_hand_after
    )
    db.add(IdempotencyKey(key=key, fingerprint=fp, response_body=result.model_dump_json()))
    try:
        db.commit()  # movement, stock and key commit together, before the response
    except IntegrityError:
        db.rollback()  # another request with this key won the race
        replay = find_replay(db, key, fp)
        if replay is None:
            raise
        return replay, True
    return result, False

The except IntegrityError branch handles two retries that arrive at the same moment. Both miss the lookup, both try to insert the key, and the primary key lets only one win. The loser rolls back its stock change and replays the winner's response.

The route reads the header. FastAPI's own error for a missing required header is a 422, and the idempotency draft asks for a 400, so the parameter is optional and the route raises itself. Replace the movement route in app/routes.py, and add from typing import Annotated, Header and Response from fastapi, and ProblemError from app.errors to its imports:

app/routes.py (replace add_movement)
@router.post("/{sku}/movements", status_code=201, response_model=MovementRead)
def add_movement(
    sku: Sku,
    data: MovementCreate,
    db: DB,
    response: Response,
    idempotency_key: Annotated[str | None, Header(max_length=255)] = None,
):
    if idempotency_key is None:
        raise ProblemError("Send an Idempotency-Key header with every movement")
    result, replayed = stock.record_movement(db, sku, data, idempotency_key)
    if replayed:
        response.headers["Idempotent-Replayed"] = "true"
    return result

Check: stop the server, delete stockroom.db so the mug starts at zero, and start it again. Create the mug as in stage 3, then send the same scan twice:

curl -s -i -X POST http://127.0.0.1:8000/items/MUG-0001/movements -H "Content-Type: application/json" -H "Idempotency-Key: scan-001" -d '{"kind": "receive", "quantity": 10}'curl -s -i -X POST http://127.0.0.1:8000/items/MUG-0001/movements -H "Content-Type: application/json" -H "Idempotency-Key: scan-001" -d '{"kind": "receive", "quantity": 10}'

Both answers are 201 Created with the same body, {"id":1,"sku":"MUG-0001","kind":"receive","quantity":10,"on_hand_after":10}. Only the second has idempotent-replayed: true among its headers. GET /items/MUG-0001 shows on_hand of 10, not 20.

Put it in order5 steps

Put the steps of one new movement in record_movement in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Stage 6: tests that prove the rules

You checked every stage by hand. Now make the checks permanent, with the tools from Testing FastAPI and pytest in Depth. A fixture gives each test a fresh in-memory database, and dependency_overrides points the app at it. StaticPool keeps one connection, because each new connection to sqlite:// would be a new, empty database.

tests/conftest.py
from collections.abc import Iterator
 
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.pool import StaticPool
 
from app.db import Base, get_db
from app.main import app
 
 
@pytest.fixture
def client() -> Iterator[TestClient]:
    engine = create_engine(
        "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
    )
    Base.metadata.create_all(engine)
    TestSession = sessionmaker(bind=engine, expire_on_commit=False)
 
    def override_get_db() -> Iterator[Session]:
        with TestSession() as db:
            yield db
 
    app.dependency_overrides[get_db] = override_get_db
    yield TestClient(app)
    app.dependency_overrides.clear()

The tests read like the rules of the business:

tests/test_stock.py
import pytest
 
 
def make_mug(client):
    response = client.post("/items", json={"sku": "MUG-0001", "name": "Blue mug"})
    assert response.status_code == 201
 
 
def move(client, kind, quantity, key):
    return client.post(
        "/items/MUG-0001/movements",
        json={"kind": kind, "quantity": quantity},
        headers={"Idempotency-Key": key},
    )
 
 
def test_receive_then_pick(client):
    make_mug(client)
    assert move(client, "receive", 10, "k1").json()["on_hand_after"] == 10
    assert move(client, "pick", 3, "k2").json()["on_hand_after"] == 7
    assert client.get("/items/MUG-0001").json()["on_hand"] == 7
 
 
def test_cannot_pick_more_than_on_hand(client):
    make_mug(client)
    move(client, "receive", 2, "k1")
    response = move(client, "pick", 5, "k2")
    assert response.status_code == 409
    assert response.headers["content-type"] == "application/problem+json"
    assert client.get("/items/MUG-0001").json()["on_hand"] == 2
 
 
def test_retry_with_same_key_is_replayed(client):
    make_mug(client)
    first = move(client, "receive", 4, "retry-me")
    second = move(client, "receive", 4, "retry-me")
    assert second.json() == first.json()
    assert second.headers["idempotent-replayed"] == "true"
    assert client.get("/items/MUG-0001").json()["on_hand"] == 4
 
 
def test_same_key_different_body_is_rejected(client):
    make_mug(client)
    move(client, "receive", 4, "k1")
    assert move(client, "receive", 9, "k1").status_code == 422
 
 
def test_duplicate_sku_is_a_conflict(client):
    make_mug(client)
    response = client.post("/items", json={"sku": "MUG-0001", "name": "Another mug"})
    assert response.status_code == 409
 
 
@pytest.mark.parametrize(
    "body",
    [
        {"kind": "pick", "quantity": 0},
        {"kind": "steal", "quantity": 1},
        {"kind": "receive", "quantity": "lots"},
    ],
)
def test_bad_movements_are_422(client, body):
    make_mug(client)
    response = client.post("/items/MUG-0001/movements", json=body, headers={"Idempotency-Key": "k"})
    assert response.status_code == 422
 
 
def test_missing_key_is_400(client):
    make_mug(client)
    response = client.post("/items/MUG-0001/movements", json={"kind": "receive", "quantity": 1})
    assert response.status_code == 400
uv run pytest -v
tests/test_stock.py::test_receive_then_pick PASSED                       [ 11%]
tests/test_stock.py::test_cannot_pick_more_than_on_hand PASSED           [ 22%]
tests/test_stock.py::test_retry_with_same_key_is_replayed PASSED         [ 33%]
tests/test_stock.py::test_same_key_different_body_is_rejected PASSED     [ 44%]
tests/test_stock.py::test_duplicate_sku_is_a_conflict PASSED             [ 55%]
tests/test_stock.py::test_bad_movements_are_422[body0] PASSED            [ 66%]
tests/test_stock.py::test_bad_movements_are_422[body1] PASSED            [ 77%]
tests/test_stock.py::test_bad_movements_are_422[body2] PASSED            [ 88%]
tests/test_stock.py::test_missing_key_is_400 PASSED                      [100%]
 
============================== 9 passed in 0.05s ===============================

Check: nine passed, and uv run ruff check . and uv run ruff format --check . are both clean. Now break a rule on purpose. In record_movement, delete Item.on_hand + change >= 0 from the where and run the tests again. The CHECK constraint now raises an IntegrityError that nothing catches, so test_cannot_pick_more_than_on_hand fails instead of getting a clean 409. Put it back.

These tests use SQLite for speed. Testing with Real Databases explains why the version you trust should also run against Postgres, where two concurrent picks are a real race you can test with threads.

Make it yours

The core works. These would make it worth showing:

  • Postgres and Alembic. Run Postgres in Docker, set STOCKROOM_DATABASE_URL, replace create_all with an Alembic migration, and add a test with two threads picking the last item at once.
  • Movement history with keyset pagination. Add GET /items/{sku}/movements that pages on (created_at, id) with an opaque cursor, as in List Endpoints That Scale.
  • Problem Details for 422s too. Add a handler for RequestValidationError so validation errors use the same shape, with the field errors in an errors member.
  • Who may move stock. Protect movements with a JWT from Authentication and JWTs, store who made each movement, and let only managers create items.
  • Low-stock alerts. When on_hand_after drops below a reorder level, write an outbox row in the same transaction and let a worker send the alert, as in Task Queues with Celery.
  • Ship it. Add a Dockerfile, a CI workflow that runs Ruff and pytest, and deploy it, following CI/CD for Python and Deploying FastAPI.

When it is done, write it up with the Interview Prep lesson Writing Project Case Studies.

Build it for real in the Project Lab

  • Sticky notes, sorted is a browser front end for exactly this kind of CRUD data: create, move and save items by status.

The rest of the FastAPI builds, from a Redis leaderboard to WebSocket chat rooms, are in the Project Lab.

Key terms
service layer
The module that holds the business rules and owns the transaction, between thin routes and the database.
conditional update
An UPDATE whose WHERE clause includes the rule, like enough stock, so the check and the change happen in one atomic statement.
lost update
A race where two requests read the same value and both write, so one change silently overwrites the other.
CHECK constraint
A rule the database enforces on every row, such as on_hand >= 0, whatever the application code does.
idempotency key
A client-generated id sent with a request so the server can recognise retries and replay the first response.
request fingerprint
A hash of the canonical request body, stored with the key, to detect a key reused for a different request.
dependency override
Replacing a dependency such as get_db in tests with app.dependency_overrides, so the app uses a test database.

That is a stock service you could put in front of real scanners. The wrap-up next pulls the whole course together around one more realistic feature, from an empty branch to a watched rollout.