How to do the migration in FastAPI

Madhav Kothari
2 min readDec 15, 2022

--

A “migration” is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc.

So, inbuild fastAPI does not provide anything to migrate out model changes to the database unlike Django, and here comes alembic into the picture. So, what is alembic for

Alembic is a lightweight database migration tool for usage with the SQLAlchemy Database Toolkit for Python.

Now, how to use this

  1. First, we have to install alembic inside our local virtual environment
pip install alembic

2. Then, we have to initialize alembic

alembic init alembic

3. After initialization it will create a file name “alembic.ini”, now open this file and you will get “sqlalchemy.url” so here you have to give your SQLAlchemy URL is all that’s needed but without commas

In my case, because I am using SQLite dB

sqlalchemy.url = sqlite:///database.db

4. Now, you have to just run the migrations like

alembic revision -m "first migrations"

then

alembic upgrade head

All done !!

After running it will create your migration file under alembic/versions

BUT …… if you check the migration file

There is no code under “upgrade()” or “downgrade()”

because this is manual migration you have to write code under these functions but there is one more way to make migrations automatic

So for that, we have to do some changes in the env.py file under the alembic folder initially target_metadata = None

We have to set this target_metadata to our model base in my case there is a user_model.py file under the models folder and my code is like this -

from models.user_model import Base
target_metadata = Base.metadata

Now we have set our target_metadata after that we have to run

alembic revision --autogenerate -m "initial migrations"

again this will create a migration file under alembic/versions but now you will see some code under these two functions “upgrade()” or “downgrade()”

Now run

alembic upgrade head

one more thing if you have more than one model file then your target_metadata should be like this:

from db.connection import Base
# This two won't be referenced, but *have* to be imported to populate `Base.metadata`
from models import user_model, bills_model
target_metadata = Base.metadata

This Base comes from your database connection in my case database connection is in my db/connection

Happy Learning !!

Source -:

https://fastapi.tiangolo.com/tutorial/sql-databases/#alembic-note

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Madhav Kothari
Madhav Kothari

Responses (1)

Write a response