Menu

FastAPI: Write Standard CRUD with SQLAlchemy 2.0 — Session Dependency and select() in 5 Minutes
📰

FastAPI: Write Standard CRUD with SQLAlchemy 2.0 — Session Dependency and select() in 5 Minutes

DEV Community: fastapi·Linh Fish Dev·about 8 hours ago
#HdlNDPDG
#devtofastapi#devto#dev#session#db_item
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.