An auto-initialised dockerised starter stack containing the following components (all on latest versions):
- FastAPI backend with single & bulk CRUD endpoints
- Postgres 16 database
- SQLAlchemy 2.0+ ORM (Async)
- Alembic Migrations (with auto-migrate on db create)
- Pydantic Validations
- Pytests with new DB created for each run
Project homepage: https://github.com/pavdwest/fastapi_pg_sqlalchemy_async_starter
- Docker
- Git (optional but recommended)
-
Clone repo:
git clone [email protected]:pavdwest/fastapi_pg_sqlalchemy_async_starter.git
-
Enter directory:
cd fastapi_pg_sqlalchemy_async_starter
-
(Optional) Create & activate virtual environment for local development:
python -m venv services/backend/app/.ignore/venv && source services/backend/app/.ignore/venv/bin/activate
-
(Optional) Install dependencies for local development/intellisense:
pip install -r services/backend/app/requirements/base.txt
-
Run stack (we attach only to the backend as we don't want to listen to PGAdmin4 spam):
docker compose up --build --attach backend
-
Everything's running:
-
Run migrations with Alembic (if you want the Books model for testing/demo purposes):
docker compose exec backend alembic upgrade head
-
Init
docker compose exec backend alembic init -t async src/migrations
-
Setup DB config
See changes to services/backend/app/src/migrations/env.py
-
Create first migration
docker compose exec backend alembic revision -m "Init" --autogenerate
-
Run first migration
docker compose exec backend alembic upgrade head
You can access PGAdmin4 at http://127.0.0.1:5050.
See the pgadmin
service in the docker-componse.yml
file for credentials.
Once you've logged into PGAdmin add the db server using the details as per db
service in the docker-componse.yml
. Tip: Host name/address is db
(name of the service) by default.
A note on conventions: https://stackoverflow.com/questions/4702728/relational-table-naming-convention/4703155#4703155
-
Add folder to
services/backend/app/src/modules
.../models/my_model/routes.py
for the endpoints.../models/my_model/models.py
for the SQLAlchemy model.../models/my_model/validators.py
for the Pydantic validators -
Import models to
services/backend/app/src/migrations/env.py
-
Create migration:
docker exec -it fastapi_pg_sqlalchemy-backend-1 alembic revision --autogenerate -m "Add MyModel"
-
Run migration:
docker exec -it fastapi_pg_sqlalchemy-backend-1 alembic upgrade head"
docker compose scale worker=10
TODO
Most likely Redis/RabbitMQ/Celery
There is currently no concept of multi-tenancy. Will likely implement multi-tenancy at schema (most likely the best middle-ground between separation and amount of admin) or database level. Row-level separation makes me uncomfortable for a number of reasons.
TODO
TODO
Currently uses all operations, create, read, update and delete. Might consider create only, but that brings with it its own slew of complications. Does simplify write-scalability and auditing.