This my current vision of the good FastAPI structure.
Short description of this structure and changes:
- Added Memory Leak Detector
- Added AI Assistent for Code Review
- Separation check action to two - check code style and check pytest
- Added Metrics Collector
- Some small changes in the code
- Added Slack Integrations for notifications
- Some small changes in the code
- Added Tracer Sample Rate Control if we want to reduce the load on the server in a production environment
- Added loguru as an option for logging and selector between loguru and standard logging
- Added Open Telemetry to project
- Added logger' and tracer' managers
- Added locust tests
- Added mypy, ruff checkers
- Added actions for GitHub
- Added transaction manager to handle the database transactions
- Take beyond the logic from the API endpoints and put it in the middle layer
- Added SQLAlchemy models and linked them with Pydantic schemas through to_read_model
- Changed orm_mode for schemas class Config to from_attributes (for Pydantic v2)
- Added Service layer to handle the logic of the API endpoints
- Added Repository layer to handle the logic of the database (based on dependency inversion principle from SOLID principles)
TODO:
- Add tests
- Add abstract class for choosing DB
- Add PostgreSQL database
- Add logger
- For autogenerated migration files for updating DB, run (NB! you need to add paths to models to the migrations/env file if you want to autogenerate migration successfully (as this moment I don't know why)):
alembic revision --autogenerate -m "description_of_changes"
- For running the migration, run:
alembic upgrade head
- For running check of the code with Ruff, run:
ruff check app
- For running the formatting of the code with the Ruff, run:
ruff format app
- For checking the code with Mypy, run:
mypy app
- For running pytest, use commands from directory:
pytest app/tests -v
- Loading testing, use:
locust -f app/tests/locust/users.py --host http://localhost:8001
- For running this project locally from root dir, run (you can use any port that you want):
uvicorn app.main:app --reload --host 0.0.0.0 --port 8001
- Before running the project in docker create docker network:
docker network create test-fastapi-sql-network
- Run the project in docker:
docker-compose up --build
-
If you want to work with collected data locally, use TRACE_INSECURE=True and TRACE_USE_CREDENTIALS=False. If you want to use external Aspecto service, use TRACE_INSECURE=False and TRACE_USE_CREDENTIALS=True
-
In Elasticseach please go to Dev Tools for finding count of metrics. For example
GET /_cat/indices?v
GET /.ds-metrics-*/_mapping
GET /.ds-metrics-*/_search
{
"query": {
"exists": {
"field": "labels.Counter"
}
}
}
- Bandit is a tool designed to find common security issues in Python code.
bandit -r app