12. Databases & SQLAlchemy
Most real-world applications need to persist data. SQLAlchemy is the most popular ORM (Object Relational Mapper) for Python. It allows you to interact with databases using Python objects instead of writing raw SQL. FastAPI integrates seamlessly with SQLAlchemy for database operations. To test these examples, install SQLAlchemy with pip install sqlalchemy and run the code locally.
What is an ORM?
An ORM maps database tables to Python classes. Each row in the database becomes an instance of a class. This abstraction allows you to work with your database using familiar Python syntax instead of writing complex SQL queries.
# Without ORM (raw SQL) cursor.execute("SELECT * FROM users WHERE age > 18") users = cursor.fetchall() # With SQLAlchemy ORM users = session.query(User).filter(User.age > 18).all()
ORM Benefits
ORMs prevent SQL injection by automatically escaping parameters, provide database abstraction (switch from SQLite to PostgreSQL with minimal changes), and make your code more maintainable.
Installing SQLAlchemy
pip install sqlalchemy pip install asyncpg # For PostgreSQL with async pip install databases # For async support
Defining Database Models
SQLAlchemy models define the structure of your database tables. Each class attribute represents a column.
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from datetime import datetime Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) email = Column(String, unique=True, index=True, nullable=False) username = Column(String, unique=True, index=True, nullable=False) hashed_password = Column(String, nullable=False) is_active = Column(Boolean, default=True) created_at = Column(DateTime, default=datetime.utcnow) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) posts = relationship("Post", back_populates="author") class Post(Base): __tablename__ = "posts" id = Column(Integer, primary_key=True, index=True) title = Column(String, index=True, nullable=False) content = Column(String, nullable=False) published = Column(Boolean, default=False) created_at = Column(DateTime, default=datetime.utcnow) author_id = Column(Integer, ForeignKey("users.id")) author = relationship("User", back_populates="posts")
Base.metadata.create_all(engine) after creating your engine.Database Session Management
Create a dependency that provides a database session to your endpoints. This ensures sessions are properly opened and closed.
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, Session from fastapi import FastAPI, Depends DATABASE_URL = "sqlite:///./test.db" engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get("/users") def get_users(db: Session = Depends(get_db)): users = db.query(User).all() return users
Async Database with SQLAlchemy
For better performance, use async database drivers with SQLAlchemy's async extension.
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from fastapi import FastAPI, Depends DATABASE_URL = "sqlite+aiosqlite:///./test.db" engine = create_async_engine(DATABASE_URL, echo=True) AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) app = FastAPI() async def get_db(): async with AsyncSessionLocal() as session: yield session @app.get("/users") async def get_users(db: AsyncSession = Depends(get_db)): from sqlalchemy import select result = await db.execute(select(User)) users = result.scalars().all() return users
Database Migrations with Alembic
Alembic is the migration tool for SQLAlchemy. It tracks changes to your models and generates migration scripts.
# Install Alembic pip install alembic # Initialize Alembic alembic init alembic # Generate a migration after changing models alembic revision --autogenerate -m "create users table" # Apply migrations alembic upgrade head # Rollback last migration alembic downgrade -1
Knowledge Check
Ready to test your understanding of 12. Databases & SQLAlchemy?