[Tutorial] FastAPI with SQLAlchemy Async ORM and Alembic

Ahmed Nafies
6 min readMar 28, 2022

If you go through the FastAPI docs, you will see that the recommended way to use SQLAlchemy asynchronously is by using the package databases and SQLAlchemy core since SQLAlchemy ORM did not have support for async operations. I have already created a tutorial describing how to use FastAPI with databases with SQLAlchemy core. But now SQLAlchemy ORM with support for async is finally here. The full code can be found here on Github.

I would recommend checking out this tutorial first.

First, let's start with our development environment, I will be using Docker and Pipenv but feel free to use your favorite Python package manager. I’ll be using Python 3.9.

Dependencies

  1. fastapi
  2. sqlalchemy ≥ 1.4
  3. Alembic
  4. asyncpg
  5. uvicorn

let’s create our virtual-env and install our initial dependencies.

pipenv install fastapi sqlachemy alembic asyncpg uvicorn

Postgres

we will utilize the power of Docker to pull a Postgres db.

docker run \
--rm \
--name postgres \
-p 5432:5432 \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=postgres \
-e POSTGRES_DB=postgres \
-d postgres

Let’s test our database.

docker exec -it postgres psql -U postgres

To exit from the Postgres shell.

#\q

Application

Here is our directory structure

dir
|__ config.py
|__ database.py
|__ models.py
|__ views.py
|__ main.py

Application Config

Create config.py file and add the database configuration.

import osclass Config:
DB_USER = os.getenv("DB_USER", "postgres")
DB_PASSWORD = os.getenv("DB_PASSWORD", "postgres")
DB_NAME = os.getenv("DB_NAME", "postgres")
DB_HOST = os.getenv("DB_HOST", "localhost")
DB_CONFIG = f"postgresql+asyncpg://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}"

--

--