Database Integration with SQLAlchemyLesson 3.1
How to connect FastAPI to PostgreSQL using SQLAlchemy
SQLAlchemy engine, SessionLocal, Base declarative, DATABASE_URL, environment variables, connection pooling, database.py pattern
Connecting FastAPI to PostgreSQL
SQLAlchemy is the standard ORM for Python. FastAPI has no built-in ORM — you wire SQLAlchemy manually. The convention is a database.py file that creates the engine and session factory.
Install dependencies
pip install sqlalchemy psycopg2-binary python-dotenvdatabase.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
DATABASE_URL = os.getenv(
"DATABASE_URL",
"postgresql://user:password@localhost/dbname"
)
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
Base = declarative_base()
engine manages the connection pool. SessionLocal is a factory — call it to get a session object. Base is the base class all ORM models inherit from.
Inject the session with a yield dependency
from .database import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Never create sessions directly inside route handlers. Always inject via Depends(get_db) so sessions are guaranteed to close after each request, even on failure.
