Difficulty: Intermediate
How do you integrate a relational database with FastAPI using SQLAlchemy?
The recommended pattern is to use SQLAlchemy (sync or async) with a dependency that provides a database session per request and closes it afterwards.
For async databases, use `sqlalchemy.ext.asyncio` with `AsyncSession`. The session dependency is the canonical FastAPI pattern:
1. Create the SQLAlchemy engine and `SessionLocal` 2. Create a `get_db` dependency that yields a session and closes it on completion 3. Inject `get_db` in route handlers to get the session
Alternatives include Tortoise ORM (async-native), Databases (lightweight async), and Prisma Python.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session, DeclarativeBase
from fastapi import FastAPI, Depends
from typing import Generator
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class Base(DeclarativeBase):
pass
# Dependency - yields DB session per request
def get_db() -> Generator[Session, None, None]:
db = SessionLocal()
try:
yield db
finally:
db.close()
app = FastAPI()
@app.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
SQLAlchemy, session, dependency, async ORM