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.

FastAPI

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

Starlette

Pydantic

ASGI specification

Uvicorn server

Alembic

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
├── README.md
├── alembic.ini
├── app
│ ├── __init__.py
│ ├── config
│ │ ├── __init__.py
│ │ ├── prod.env
│ │ └── qa.env
│ ├── database.py
│ ├── main.py
│ ├── models
│ │ ├── __init__.py
│ └── schemas
├── migration
│ ├── README
│ ├── env.py
│ ├── script.py.mako
│ └── versions
│ └── 66d8a54cd297_initial_tables.py
├── start.sh

Create a directory config and have environment configurations there.

#__init__.py
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"

Alembic

# Initialize alembic database migration flow
$ alembic init db-migration
  • Update alembic’s env.py 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
env.py

Alembic autogeneration of migration scripts

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

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

Summary

  • 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