Consider a FastAPI endpoint that uses a database session dependency but forgets to close the session after use. What is the likely outcome?
from fastapi import FastAPI, Depends from sqlalchemy.orm import Session app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: pass # missing db.close() @app.get("/items/") def read_items(db: Session = Depends(get_db)): return db.query(Item).all()
Think about what happens if you open a resource but never close it.
If the database session is not closed, connections stay open and can exhaust the connection pool, leading to errors in subsequent requests.
Choose the code snippet that correctly creates and closes a SQLAlchemy session using FastAPI dependency injection.
Consider how to guarantee cleanup even if an error occurs.
Using try-finally ensures db.close() runs no matter what happens during yield.
Given this FastAPI dependency for database session management, what is the state of the session after the endpoint returns?
def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get("/users/") def read_users(db: Session = Depends(get_db)): users = db.query(User).all() return users
Look at what happens in the finally block.
The finally block calls db.close(), so the session is closed and resources freed after the endpoint finishes.
Examine the code below. Why does the app raise 'InvalidRequestError: Session is closed' when trying to query the database?
def get_db(): db = SessionLocal() try: db.close() yield db except Exception: db.rollback() @app.get("/products/") def read_products(db: Session = Depends(get_db)): products = db.query(Product).all() return products
Check the order of yield and db.close() calls.
db.close() is called before the yield, so the session closes before the endpoint uses it, causing the error.
What is the main advantage of using dependency injection to manage database sessions in FastAPI applications?
Think about resource management and request isolation.
Dependency injection provides a new session per request and ensures it closes properly, avoiding leaks and conflicts.