How to Use Dependency for DB Session in FastAPI
In FastAPI, use
Depends to inject a database session dependency into your path operation functions. Define a function that creates and closes the DB session, then use it as a dependency parameter with Depends(get_db) to access the session safely.Syntax
To use a database session as a dependency in FastAPI, you define a function that yields a session object. This function handles opening and closing the session. Then, you add a parameter to your route function with Depends to get the session injected automatically.
- get_db(): Function that creates and yields the DB session.
- Depends(get_db): Declares the dependency in your route.
- db: The session object you use inside your route.
python
from fastapi import Depends from sqlalchemy.orm import Session # Assuming SessionLocal is defined elsewhere def get_db(): db = SessionLocal() # create session try: yield db # provide session finally: db.close() # close session @app.get("/items/") def read_items(db: Session = Depends(get_db)): # use db session here pass
Example
This example shows a complete FastAPI app using SQLAlchemy. It defines a get_db dependency that creates and closes a session. The read_users route uses this session to query users from the database.
python
from fastapi import FastAPI, Depends from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker, declarative_base, Session DATABASE_URL = "sqlite:///./test.db" engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() class User(Base): __tablename__ = "users" 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.get("/users/") def read_users(db: Session = Depends(get_db)): users = db.query(User).all() return users
Output
[
]
Common Pitfalls
Not closing the session: Forgetting to close the DB session can cause connection leaks. Always use try/finally with yield to ensure closure.
Not using Depends: Passing the session directly without Depends breaks FastAPI's dependency injection and lifecycle management.
python
from fastapi import Depends from sqlalchemy.orm import Session # Wrong: no yield, no close def get_db_wrong(): db = SessionLocal() return db @app.get("/items_wrong/") def read_items_wrong(db: Session = get_db_wrong()): # This will not close session properly pass # Right way def get_db(): db = SessionLocal() try: yield db finally: db.close()
Quick Reference
- Define a
get_dbfunction that yields a session and closes it after use. - Use
Depends(get_db)in your route parameters to get the session. - Always close the session to avoid connection leaks.
- Use SQLAlchemy's
sessionmakerto create sessions.
Key Takeaways
Use a generator function with yield to create and close the DB session safely.
Inject the DB session into routes using Depends(get_db) for automatic management.
Always close the session in a finally block to prevent connection leaks.
Avoid returning the session directly without yield to keep FastAPI lifecycle intact.
Use SQLAlchemy sessionmaker to create sessions bound to your database engine.