SQLAlchemy Setup in Python

From the FastAPI cheat sheet · Database Integration · verified Jul 2026

SQLAlchemy Setup

Configure SQLAlchemy with FastAPI using dependency injection.

python
# database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase

engine = create_engine("sqlite:///./app.db")
SessionLocal = sessionmaker(bind=engine)

class Base(DeclarativeBase):
    pass
💡 Use the yield dependency pattern to ensure DB sessions are always closed
⚡ For PostgreSQL, install: pip install psycopg2-binary
📌 check_same_thread is only needed for SQLite — remove it for other databases
🟢 Call Base.metadata.create_all() once at startup to create tables
databasesqlalchemysetup

Continue with FastAPI

Save the full cheat sheet or work through every related task.

More Python tasks

Back to the full FastAPI cheat sheet