0
0
FastapiHow-ToBeginner · 3 min read

How to Use Dependency for Database in FastAPI

In FastAPI, use Depends to declare a database session as a dependency that can be injected into path operations. Define a function that creates and yields a database session, then use Depends to pass it to your route handlers for safe and reusable database access.
📐

Syntax

To use a database dependency in FastAPI, define a function that creates and yields a database session. Use Depends in your path operation function parameters to receive the session.

  • def get_db(): - Function to create and yield a database session.
  • yield db - Provides the session to the caller and ensures cleanup after use.
  • db: Session = Depends(get_db) - Injects the session into your route handler.
python
from fastapi import Depends
from sqlalchemy.orm import Session

# Assume SessionLocal is already defined elsewhere

def get_db():
    db = SessionLocal()  # create a new database session
    try:
        yield db  # provide the session
    finally:
        db.close()  # close session after use

@app.get("/items/")
def read_items(db: Session = Depends(get_db)):
    items = db.query(Item).all()
    return items
💻

Example

This example shows how to set up a SQLite database session dependency in FastAPI and use it in a route to fetch all items from a table.

python
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.get("/items/")
def read_items(db: Session = Depends(get_db)):
    return db.query(Item).all()
Output
HTTP GET /items/ returns JSON list of items from the database, e.g. [] if empty or [{"id":1,"name":"Sample Item"}] if data exists
⚠️

Common Pitfalls

Common mistakes include:

  • Not closing the database session, which can cause connection leaks.
  • Creating the session outside the dependency function, leading to shared sessions and concurrency issues.
  • Forgetting to use yield in the dependency function, which prevents proper cleanup.

Always create and close the session inside the dependency function using yield.

python
from fastapi import Depends
from sqlalchemy.orm import Session

# Wrong: session created once globally
# db = SessionLocal()

# Wrong: no yield, no cleanup
# def get_db():
#     db = SessionLocal()
#     return db

# Correct way:
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
📊

Quick Reference

  • Define dependency: Create a function that yields a database session.
  • Inject dependency: Use Depends(get_db) in route parameters.
  • Session management: Always close sessions in finally block.
  • Use ORM sessions: Pass Session type hints for clarity.

Key Takeaways

Use a dependency function with yield to create and close database sessions safely.
Inject the database session into routes using Depends(get_db) for clean code and reuse.
Never create a global session; always create it inside the dependency function.
Closing the session in a finally block prevents connection leaks.
Type hint your session parameter as Session for better code clarity.