Configuring Python FastAPI with SqlAlchemy and Alembic

FastAPI is a promising framework to build high performance web applications that needs Async support. It also brings in best practices for a high quality production application.

Let’s take a quick view of few building blocks that we will use in this article.


To run FastAPI based application we will need an ASGI server such as Uvicorn or Hypercorn.



ASGI specification

Uvicorn server


Getting started

# Use python 3.6+
pipenv install fastapi uvicorn sqlalchemy alembic

Uvicorn installation error

ERROR: Cannot use 'python', Python 2.4 or later is required.", '           Note that Python 3 or later is not yet supported.'

But uvicorn seems functional though installation had an error. I didn’t fully understand the reason., But it is not blocking our project.

Environment based configuration

pipenv install python-dotenv

Directory structure (end result )

├── Dockerfile
├── Pipfile
├── Pipfile.lock
├── alembic.ini
├── app
│ ├──
│ ├── config
│ │ ├──
│ │ ├── prod.env
│ │ └── qa.env
│ ├──
│ ├──
│ ├── models
│ │ ├──
│ └── schemas
├── migration
│ ├── README
│ ├──
│ ├──
│ └── versions
│ └──

Create a directory config and have environment configurations there.
from pydantic import BaseSettings
class Settings(BaseSettings):
# default conf goes here
app_name: str = "Awesome API"
admin_email: str
items_per_user: int = 50
class Config:
env_file = ".env"


# Initialize alembic database migration flow
$ alembic init db-migration
  • Update alembic’s with environment based db_url with custom get_url method as shown below
  • update run_migration_offline as shown below
  • update run_migration_online as shown below
  • update target_metadata This is needed for autogeneration of migration scripts

Alembic autogeneration of migration scripts

  • Below will help to automatically add all models that exists into __all__ so that we can do import * as shown in

We make use of autogeneration of schema changes. With this, we can make changes to database models and run autogenerate — this will generate the changes as script.

# This will scan the models and generate upgrade & downgrade scripts
alembic revision --autogenerate -m “Initial tables”

Running db migration

# following command will run all migration script and bring it to latest version
alembic upgrade head
# If we like to incrementally upgrade and check for some errors
alembic upgrade +1
# To undo last migration
alembic downgrade -1
# To get more information
alembic current
alembic history - verbose


  • Configuring alembic with fastapi and getting autogeneration working is little tricky.
  • Above setup with env based config should come handy, if you are trying to setup one.

Useful links

Software Architect ★ Data engineer ★ Committed to improve data science productivity