06.03

Repositories and transactions in FastAPI

skillmaxingPython with AIRepositories and transactions in FastAPI
Visual lesson

Repositories and transactions in FastAPI

Included with Pro · 4:31
Lessons · 974 words

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.

Where the query code lives
Figure 1Where the query code livesRoutes speak the domain. The repository speaks SQLAlchemy. Nothing else does.

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.

Pro

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.

Unlock full access to
Python with AIAI researchComplete system design
30% off with LAUNCH30ends in 7h 40m
Buy now
View all plans ·Already Pro? Sign in
124 online