SQLAlchemy & SQLModel

Using an ORM

Real projects usually use an ORM: SQLAlchemy 2.0 (the standard) or SQLModel (by FastAPI's author; one class serves as both table and Pydantic model).

# pip install sqlmodel
from typing import Annotated
from fastapi import Depends, FastAPI
from sqlmodel import Field, Session, SQLModel, create_engine, select

class Course(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    title: str = Field(index=True)
    level: str = "basic"

engine = create_engine("postgresql+psycopg://app:secret@localhost/app")

def get_session():
    with Session(engine) as session:
        yield session

SessionDep = Annotated[Session, Depends(get_session)]
app = FastAPI()

@app.post("/courses")
def create_course(course: Course, session: SessionDep) -> Course:
    session.add(course)
    session.commit()
    session.refresh(course)
    return course

@app.get("/courses")
def list_courses(session: SessionDep, level: str | None = None) -> list[Course]:
    query = select(Course)
    if level:
        query = query.where(Course.level == level)
    return session.exec(query).all()

Migrations

Do not create tables from code in production. Use Alembic to version the schema:

alembic init migrations
alembic revision --autogenerate -m "create courses table"
alembic upgrade head