[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…

--

--

Ahmed Nafies
Ahmed Nafies

Responses (5)