Alembic + FastAPI + PostgreSQL = ✅
If you're using FastAPI and PostgreSQL, and want to manage migrations the right way, Alembic is the tool. But the official docs can feel like a maze.
This is my minimal setup — no buzzwords, no frameworks on top of frameworks, just working code.
1. Project Layout
Here's the file structure I use:
project/
├── app/
│ ├── models/
│ │ └── user.py
│ ├── db/
│ │ ├── base.py
│ │ └── session.py
│ └── main.py
├── alembic/
├── alembic.ini
├── .env
├── requirements.txt2. Install Dependencies
fastapi
sqlalchemy
alembic
psycopg2-binary
python-dotenv
pip install -r requirements.txt3. The .env file
DATABASE_URL=postgresql://postgres:password@localhost:5432/mydbUsing Docker for PostgreSQL? I wrote a 10-min PostgreSQL Docker guide that you can follow.
4. SQLAlchemy Model
app/models/user.py
from sqlalchemy import Column, Integer, String
from app.db.base import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)5. Setup Base and Session
#app/db/base.py
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
#app/db/session.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)6. Initialize Alembic
alembic init alembicThen edit alembic/env.py to use .env and your Base:
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
import os
from dotenv import load_dotenv
load_dotenv()
from app.db.base import Base
from app.models import user
config = context.config
config.set_main_option("sqlalchemy.url", os.getenv("DATABASE_URL"))
fileConfig(config.config_file_name)
target_metadata = Base.metadata7. Migrate and Apply
Generate the migration:
alembic revision --autogenerate -m "create users table"Apply:
alembic upgrade headDone.
8. Example: Add a New Column
Modify your User model:
age = Column(Integer, nullable=True)Then:
alembic revision --autogenerate -m "add age column to users"
alembic upgrade headTL;DR Cheatsheet
alembic init alembic
alembic revision --autogenerate -m "your message"
alembic upgrade headClosing Notes
- No Pydantic here. Just SQLAlchemy and Alembic.
- No fancy folder structure. Just what works.
- Want a GitHub repo with this setup? DM me.
- Want to connect? unartech.in is where I'm building stuff.