Database session management helps your app talk to the database safely and efficiently. It keeps track of changes and makes sure data is saved or rolled back properly.
Database session management in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from sqlalchemy.orm import Session from fastapi import Depends def get_db(): db = SessionLocal() try: yield db finally: db.close()
This function creates a database session and closes it after use.
Use Depends(get_db) in your path operation to get the session.
from fastapi import FastAPI, Depends from sqlalchemy.orm import Session app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get("/items/") def read_items(db: Session = Depends(get_db)): items = db.query(Item).all() return items
from fastapi import Depends from sqlalchemy.orm import Session @app.post("/items/") def create_item(item: ItemCreate, db: Session = Depends(get_db)): db_item = Item(**item.dict()) db.add(db_item) db.commit() db.refresh(db_item) return db_item
This FastAPI app connects to a SQLite database. It manages sessions with get_db. You can add items and list all items. The session opens for each request and closes after.
from fastapi import FastAPI, Depends from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker, declarative_base, Session SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() class Item(Base): __tablename__ = "items" id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) Base.metadata.create_all(bind=engine) app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.post("/items/") def create_item(name: str, db: Session = Depends(get_db)): db_item = Item(name=name) db.add(db_item) db.commit() db.refresh(db_item) return {"id": db_item.id, "name": db_item.name} @app.get("/items/") def read_items(db: Session = Depends(get_db)): items = db.query(Item).all() return [{"id": item.id, "name": item.name} for item in items]
Always close the session to avoid database connection leaks.
Use commit() to save changes and refresh() to get updated data like auto-generated IDs.
Use yield in get_db to create a clean way to open and close sessions per request.
Database session management helps your app safely talk to the database.
Use a function like get_db to open and close sessions for each request.
Use the session to add, query, and commit data inside your FastAPI routes.
Practice
get_db function in FastAPI when working with databases?Solution
Step 1: Understand the role of
Theget_dbget_dbfunction is designed to open a database session when a request starts and close it when the request ends.Step 2: Recognize safe database session management
This ensures that each request has its own session, preventing conflicts and resource leaks.Final Answer:
To create and close a database session for each request safely -> Option AQuick Check:
Database session management = create and close session [OK]
- Thinking get_db stores data permanently
- Confusing get_db with HTTP request handling
- Assuming get_db generates HTML
Depends?Solution
Step 1: Understand FastAPI dependency injection syntax
FastAPI usesDependsto inject dependencies like database sessions into route functions.Step 2: Correct syntax for session injection
The correct syntax is to type hint the parameter asSessionand assign itDepends(get_db)to call the dependency function.Final Answer:
def read_items(db: Session = Depends(get_db)): -> Option DQuick Check:
Dependency injection = parameter: Type = Depends(function) [OK]
- Calling get_db() directly in parameter default
- Using Depends with a class instead of a function
- Swapping parameter and default values
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
app = FastAPI()
def get_db():
db = Session()
try:
yield db
finally:
db.close()
@app.get('/items')
def read_items(db: Session = Depends(get_db)):
items = db.query(Item).all()
return itemsSolution
Step 1: Analyze the get_db function behavior
Theget_dbfunction creates a session, yields it for use, then closes it safely after the request.Step 2: Understand the route's database query
The route uses the session to query allItemrecords and returns them as a list.Final Answer:
A list of all items from the database -> Option CQuick Check:
Yielded session + query = list of items [OK]
- Assuming session is not closed causing error
- Thinking yield causes syntax error
- Believing query returns empty without data
def get_db():
db = Session()
yield db
db.close()
@app.post('/add')
def add_item(item: Item, db: Session = Depends(get_db)):
db.add(item)
db.commit()Solution
Step 1: Review session closing in get_db
Thedb.close()is called after yield without a try-finally block, so if an exception happens, the session may never close.Step 2: Understand proper session cleanup
Using try-finally ensures the session closes even if errors occur during request handling.Final Answer:
The session is closed after yield, so it may not close if an exception occurs -> Option BQuick Check:
Session close needs try-finally for safety [OK]
- Ignoring try-finally for session cleanup
- Forgetting to commit changes
- Misplacing Depends usage
get_db implementations best achieves this?Solution
Step 1: Understand transaction management needs
We want to commit changes only if no errors occur, otherwise rollback to avoid partial changes.Step 2: Analyze each get_db implementation
def get_db(): db = Session() try: yield db db.commit() except: db.rollback() raise finally: db.close() uses try-except-finally to commit on success, rollback on error, and always close the session, which is the safest approach.Final Answer:
def get_db(): db = Session() try: yield db db.commit() except: db.rollback() raise finally: db.close() -> Option AQuick Check:
Commit on success, rollback on error, always close [OK]
- Committing after yield without error handling
- Not rolling back on exceptions
- Closing session without try-finally
