FastAPI Quickstart part 08: Database Migration with Alembic and SQLAlchemy | #python #fastapi #letscode

Posted by

FastAPI Quickstart part:08 DB Migration using Alembic + SQLAlchemy

FastAPI Quickstart part:08 DB Migration using Alembic + SQLAlchemy

Today, we will be discussing how to perform database migrations using Alembic and SQLAlchemy within a FastAPI project. This is an essential aspect of any application development, as it allows us to make changes to our database schema without losing any data.

Firstly, let’s ensure that we have both Alembic and SQLAlchemy installed in our FastAPI project. You can do this by running the following commands:


pip install alembic
pip install sqlalchemy

Now, we need to set up our Alembic configuration file. This can be done by running the following command within your FastAPI project directory:


alembic init alembic

This will create a new directory called ‘alembic’ containing the necessary configuration files for Alembic. Next, let’s create a new migration script by running the following command:


alembic revision -m "create_table"

This will generate a new migration script within the ‘versions’ directory of the ‘alembic’ folder. Here, we can define the changes we want to make to our database schema using SQLAlchemy. For example, we can create a new table by adding the following code to the migration script:


from alembic import op
import sqlalchemy as sa

def upgrade():
op.create_table(
'users',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.String),
sa.Column('email', sa.String)
)

def downgrade():
op.drop_table('users')

Once we have defined the changes in our migration script, we can apply them to our database by running the following command:


alembic upgrade head

This will execute the migration script and update our database schema accordingly. Finally, don’t forget to add the necessary imports and configuration settings to your FastAPI project in order to connect to the database and interact with it using SQLAlchemy.

That’s it! You have now successfully set up and applied a database migration using Alembic and SQLAlchemy within your FastAPI project. Happy coding!

#python #fastapi #letscode