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.
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.
The scanner sends a movement and a key it generated once for this scan.
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 httpx2uv 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__.pyAdd a Ruff section to the end of pyproject.toml, as in Code Quality Tools. A line length of 100 keeps the code below readable:
[tool.ruff]
line-length = 100Then the smallest app that proves the setup works, from Your First FastAPI App:
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.pyYou 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.
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.
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.
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.
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: intPydantic 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.
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:
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:
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 itemThe 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):
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:
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 each request to the status code this API returns.
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:
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:
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, MovementReaddef 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:
@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"}db.commit() out of record_movement and into get_db, after the yield. On FastAPI 0.118 or later, what can go wrong?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:
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.
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)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:
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:
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.
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, FalseThe 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:
@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 resultCheck: 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 the steps of one new movement in record_movement in order.
- Tap the steps below in the right order.
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.
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:
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 == 400uv run pytest -vtests/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, replacecreate_allwith 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}/movementsthat pages on(created_at, id)with an opaque cursor, as in List Endpoints That Scale. - Problem Details for 422s too. Add a handler for
RequestValidationErrorso validation errors use the same shape, with the field errors in anerrorsmember. - 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_afterdrops 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.
- 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.