Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker.
There is two development modes: full-fledged docker (postgres) or simple (with sqlite and no docker).
# install poetry
curl -sSL https://install.python-poetry.org | python3 -
# create SECRET for jwt
cd backend
openssl rand -hex 32 > SECRET_KEY
# install packages
poetry install
No docker, no postgres. Just sqlite. Starts on port 8000.
cd backend
poetry shell
LOCAL_DEV=1 uvicorn app.main:app --reload
DB Browser for Sqlite is a tool similar to PGAdmin, but for sqlite databases.
Runs the fastapi server on port 8004.
$ docker-compose up -d --build
$ docker-compose exec web alembic upgrade head
docker-compose exec web alembic revision --autogenerate
docker-compose exec web alembic upgrade head
username: [email protected] password: postgres
Open the backend/
folder in your IDE
and point the python interpreter to poetry
Shows dependency graph of the backend
poetry shell
# cluster external dependencies (simplifies)
pydeps app --cluster
db.py
contains functions to start the db and get an async session.models.py
contains the models as SqlModel objects. Ideally this would be domain entities, without concerns like persistence. It is far simpler to define these in one file, at the sacrifice of binding the models to the SQLModel ORM. Limitingmodels.py
to pydantic models and creatingschema.py
or similar for SqlAlchemy divides concerns, but is more complicated.auth.py
functions dedicated to authorization and authentication. Handles persistence too (potentially too broad in scope).crud.py
generic CRUD functions that are user aware and scope db calls to a user. User code does not need to know about handling tokens, users, etc.main.py
brings fastapi in to route everything. Only file to depend on fastapi. Bigger projects may break this up into multiple routers.test_wrapper.py
provides an async client wrapper for running tests. Async client is user aware, and handles header tokens - just specify the user.test.py
the actual test cases. Useswrapper
fromtest_wrapper.py
- add models (copy form of
Song
andSongBase
) tomodels.py
.SongBase
inherits fromSQLModel
and has no table in the database; it is unaware of uuids or user ids. Often used for client facing when creating, or returning simplified models.Song
inherits fromOwned
andSongBase
, as well as specifyingtable=True
to create a table in the database. InheritingOwned
means it is aware of uuids and user ids. - add business logic either directly to
main.py
routes (simple cases) or create a new file to hold complex logic. Consider naming it after the model. Either way, use the functions incrud.py
for persistence. Ifcrud.py
is used, the models passed do not need to haveuser_id
set, it will set itself from the user id of thetoken
. - add model to
target_metdata
inbackend/migrations/env.py
- add test fixtures to
test_wrapper.py
- add test to
test.py
Trick:
song_base: SongBase = SongBase(...)
song: Song = Song(**song_base.dict())
song2: Song = Song(...)
song_base2: SongBase = SongBase(**song2.dict())
FastApi + SqlModel + Alembic - also - Article
Poetry is used for dependency management. Full docs here, but below is the basics:
# using environment
poetry shell
# installing
poetry add package-name
poetry add "package-name[extras]"
# installing (dev)
poetry add -G dev package-name
# updating packages
poetry update
Note: poetry does not work in a folder with __init__.py
FastApi's background tasks are used for backgrounds tasks.
Future options are
- ray serve (for CPU/GPU bound tasks; good for ML applications)
- celery + flower
- arq
from fastapi.concurrency import run_in_threadpool
res = await run_in_threadpool(cpu_bound_task, contents)
https://stackoverflow.com/questions/71516140/
https://www.anyscale.com/blog/serving-pytorch-models-with-fastapi-and-ray-serve
- use files for secrets instead of environment variables
- environment variables are more prone to leaking
- files can be protected by OS permissions
- blog post
Helpful random bits of info: