Repositories and transactions in FastAPI
Repositories and transactions in FastAPI
Routes that build select() statements inline work for the first five endpoints and then become the place where every bug lives. The same query gets written three slightly different ways, a filter is forgotten in one of them, and a test for a route has to stand up a database just to check a status code. A repository is a class that owns the queries for one model, takes a session, and exposes methods named after what the domain does: get, list_open_for, escalate.
The second half of the pattern is the transaction. A request that escalates a ticket writes to two tables and should either do both or neither. If the repository commits after every write, that guarantee is gone. So the repository never commits. The request does, once, at the end.
Continue reading
Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.