A dockerised multi-tenant (by schema) stack containing the following components:
- FastAPI backend
- Postgres 15 database
- SQLAlchemy ORM (Async)
- Alembic Migrations
- Pydantic Validations
TODO
-
Clone repo:
git clone [email protected]:pavdwest/fastapi_pg_sqlalchemy.git -
Enter directory:
cd fastapi_pg_sqlalchemy -
Create & activate virtual environment:
python -m venv services/backend/app/.ignore/venv && source services/backend/app/.ignore/venv/bin/activate -
Install dependencies for local development/intellisense:
pip install -r services/backend/app/requirements/base.txt -
Add .env file:
cp services/backend/app/src/.env.example services/backend/app/src/.env -
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:
http://127.0.0.1:8000/docs -
Run migrations with Alembic:
docker compose exec fastapi_pg_sqlalchemy-backend-1 alembic upgrade head
docker compose exec fastapi_pg_sqlalchemy-backend-1 alembic init -t async src/migrations
You can access PGAdmin4 at http://localhost: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.
-
Add folder to
services/backend/app/src/modules.../models/my_model/routes.pyfor the endpoints.../models/my_model/models.pyfor the SQLAlchemy model.../models/my_model/validators.pyfor 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"