Python FastAPI Tutorial (Part 15): PostgreSQL and Alembic - Database Migrations for Production
Why It Matters
Switching to PostgreSQL and Alembic gives FastAPI applications production‑grade reliability, enabling safe schema changes and robust concurrent access without risking data loss.
Key Takeaways
- •Replace SQLite with PostgreSQL for production‑grade concurrency handling.
- •Use Alembic for version‑controlled database migrations in FastAPI.
- •Store DB URL in Pydantic settings, avoiding hard‑coded credentials.
- •Remove create_all() and rely on migration scripts for schema changes.
- •Install async‑compatible psycopg driver and configure async SQLAlchemy engine.
Summary
The video walks developers through converting a FastAPI tutorial project from a development‑only SQLite database to a production‑ready PostgreSQL setup, and introduces Alembic for managing schema migrations. It explains why SQLite’s file‑based model and the use of create_all() are unsuitable for production, then shows how to install PostgreSQL locally (via Homebrew, apt, or Docker), create a dedicated user and database, and verify connectivity with psql.
Key technical steps include installing the async‑compatible psycopg driver, moving the database URL out of hard‑coded code into a Pydantic Settings class, and loading it from an .env file. The tutorial removes the create_all() call from the app lifespan, cleans up unused imports, and configures SQLAlchemy’s async engine to use the new URL. Alembic is added via uv, initialized with the async template, and its directory structure (alembic.ini, env.py, versions folder) is explained as the foundation for version‑controlled migrations.
The presenter highlights practical examples: a psql command sequence to create a user (blog_user) and database (blog), the “if not exists” limitation of create_all(), and the analogy that each Alembic migration file acts like a Git commit for the database schema. He also stresses best practices such as storing credentials in .env and adding the file to .gitignore to avoid accidental exposure.
By adopting PostgreSQL and Alembic, developers gain reliable concurrent write handling, safe incremental schema evolution, and a workflow that mirrors production environments. This transition eliminates the risk of data loss from table recreation and aligns the project with industry‑standard tooling for scalable FastAPI deployments.
Comments
Want to join the conversation?
Loading comments...