CRUD — the four create, read, update, and delete operations — is something almost every API needs. The standard way to do it in FastAPI is to put the database logic in CRUD functions built on SQLAlchemy 2.0 — select() , db.get() , db.add() , db.delete() — get the session from a yield dependency named get_db , and declare a clear response_model and status_code on each endpoint. This pattern works for any table, is easy to test with TestClient, and avoids both leaked sessions and sensitive data slipping into responses.
The Problem
Many tutorials still write CRUD by opening a session directly inside the endpoint, or by sharing one global session across all requests. A global session is unsafe when the server runs with multiple threads: two requests can interleave their commits, uncommitted data from one request can leak into another, and a session that is never closed slowly drains the connection pool.…