Complete Guide to FastAPI and Alembic Database Migration
📂 Stage: Stage 3 - Data Persistence (Database) 🔗 Related chapters: FastAPI SQLAlchemy 2.0实战 · FastAPIdependency-injection
Have you ever written by hand in a production environment?ALTER TABLESentences, so nervous that your palms sweat? Team members individually modify the database structure, eventually causing the environment to get out of control?
If you are building applications using FastAPI + SQLAlchemy, then Alembic is the tool to help you get rid of these nightmares.
This guide will take you from scratch to master every key skill in Alembic, making database changes as easy as managing code with Git.
Table of contents
Why do you need a database migration tool?
In the days before migration tools, we could only rely on handwritten SQL to modify the table structure. This "streaking" approach will quickly expose a bunch of problems:
Alembic’s Core Values
Alembic is the official migration tool launched by SQLAlchemy and is specially designed to solve the above pain points. It brings you:
- ✅ Database version control like Git
- ✅ Automatically compare the ORM model with the real database and generate a migration script
- ✅ Reversible migration, extremely safe when performing rollback
- ✅ Ensure the structure of development, testing and production environments is consistent
- ✅ Complete change history, audit records are clear at a glance
Project dependency installation
Before starting, make sure your project has the necessary dependencies installed.
All dependencies can be installed with one command:
Alembic basic concepts and project integration
Quick overview of core components
when you executealembic initAfterwards, the following key sections are generated:
env.py– A bridge connecting the database and SQLAlchemy model, every migration starts from herealembic.ini– Global configuration files (database URL, logs, etc.)versions/– A folder that stores all migration scripts, each file is a versionscript.py.mako– Migration script generation template with customizable format
FastAPI project structure recommendation
After integrating Alembic, the recommended project directory looks like this:
Initialize Alembic
In the project root directory, just one command can generate the alembic skeleton:
Configurationenv.py(key step)
Need to modify nextalembic/env.py, let Alembic know where your model is and how to connect to the database.
💡 Tip:
compare_type=Trueandcompare_server_default=TrueIt is a key parameter for automatically detecting table structure differences. It is recommended to turn it on to avoid missing subtle changes.
Simplifyalembic.ini
Keep the core configuration and delete redundant comments to make the file cleaner:
Automatically generate migration script
Basic commands
After modifying the model, only one command is needed to generate the migration script:
After execution, Alembic will compare your ORM model with the table structure of the current database and automatically generate anupgrade()anddowngrade()Function script.
How automatic generation works
- Scan all items in the project that inherit from
BaseThe SQLAlchemy model - Connect to the database and read existing tables, columns, indexes, constraints and other information
- Analyze differences (added/deleted tables, columns, type changes, etc.)
- Generate executable migration scripts, including upgrade and rollback logic
Generated script example
Below is a typical auto-generated script that will giveusersAdd a tableavatarFields:
📌 Note: Although the automatically generated script saves time and effort, it only handles "structural" changes. If your changes involve data migration or complex SQL logic, you will need to write scripts manually.
Manually write migration script
Which scenarios need to be written manually?
- New/modified fields and corresponding historical data need to be migrated at the same time
- Perform automatically generated complex operations that cannot be inferred, such as splitting tables and merging fields
- Need to finely control the execution sequence, or add conditional judgment and performance optimization
Practical combat: Convert string status to integer enumeration
Suppose we need touserstablestatusfields from string('active' / 'inactive') to integer enumeration (1 / 0), and requires smooth transformation of existing data.
🛡️ Security Tip: Before performing data migration, please be sure to fully verify it in the test environment
upgradeanddowngradeloop to ensure data is not lost.
Version control and migration commands
Dependency chain between migration files
Each migration file must passdown_revisionPoint to the previous version, thus forming a clear linked list:
headIndicates the latest version,baseRepresents an empty database state with no tables.
Quick check of commonly used commands
##Multiple environments and production environment deployment {#Multiple environments and production environment deployment}
Load different databases according to the environment
existapp/database.py, we can use environment variables to distinguish development, testing, production and other environments:
When performing a migration, simply pass inAPP_ENVThat’s it:
Integrate migrations in Docker
Alembic upgrade can be included in the Dockerfile as a necessary step before startup:
Production environment safe migration process script
In a real production environment, it is strongly recommended to use the script solidification process and add backup and manual review links:
🔒 Core Principle: Before production changes, backup + audit + secondary confirmation are indispensable.
Common Pitfalls and Best Practices
Common traps, be careful
- ❌
downgradeForgetting to consider the order of deletion - for example, deleting the table first and then deleting the index will lead to errors. Operations should be performed in the order of Delete constraints/indexes first, then delete tables. - ❌ The model is inconsistent with the current version of the database - if you change the model but haven't upgraded to the latest migrations, the automatic generation will produce weird differences. Please execute first
alembic upgrade head, keep the database up to date, then modify the model and generate new migrations. - ❌ Using row-by-row update ORM operations on large tables - will bring huge performance overhead. It is recommended to use bulk SQL or batch processing instead.
Best Practice Checklist
- 📁 Migration file naming: Use a meaningful description and prefix it with a date or serial number, such as
20260410_add_user_avatar.py, convenient for sorting and searching. - 🔄 Full upgrade and rollback: Make sure every
upgradeAll have correspondingdowngrade, and the operation is completely symmetrical, repeatedly verified in the test environmentupgrade → downgrade → upgradeNo data will be lost. - 🧪 Test migration process: Regularly perform automated migration-rollback testing in CI/CD or local test environments.
- 📀 Backup before production: No matter how small the changes are, you must back up the database before performing migration and develop a habit.
Recommended migration script template
Save the following template to standardize the format of all migration files in your team:
Summary
Alembic provides a complete database change management solution for the FastAPI + SQLAlchemy project. Through automated generation scripts, reversible migration, multi-environment support and rigorous deployment processes, it makes the evolution of the database structure transparent, safe and traceable.
💡 Key Points Review:
- Always verify migration-rollback integrity in a test environment
- Make sure each
downgradeandupgradecompletely symmetrical- Before execution in the production environment, it must be backed up, reviewed and confirmed twice.
Now, you can safely introduce Alembic into your own project and manage your database structure like code!
🔗 Extended reading

