FastAPI Best Architecture
English | 简体中文
This is a base project for the FastAPI framework, using a pseudo three-tier architecture, still in production.
It is intended to allow you to use it directly as your infrastructure to develop your project, this repository as a template library public, can be used directly
Support python3.10 and above
Pseudo three-tier architecture
In python web frameworks, the mvc architecture is the most common, but for restful users, the three-tier architecture is the way to go
But in python development, there is no universal standard for the concept of a three-tier architecture, so here I call it a pseudo three-tier architecture
workflow | java | fastapi_best_architecture |
---|---|---|
view | controller | api / view |
data validation | dto | schema |
business logic | service + impl | service |
data access | dao / mapper | crud |
model | model / entity | model |
Features
- FastAPI New Features
- Asynchronous design
- RESTful API specification
- SQLAlchemy 2.0 syntax
- Pydantic Data Validation
- Casbin RBAC Permission Control
- APScheduler Timed Tasks
- JWT Authentication
- Redis Caching
- Docker Deployment
- Pytest testing
Getting started:
1: Legacy mode
-
Install dependencies
pip install -r requirements.txt
-
Create a database
fba
, choose utf8mb4 encoding -
Install and start Redis
-
Create a
.env
file in thebackend/app/
directorycd backend/app/ touch .env
-
Copy
.env.example
to.env
cp .env.example .env
-
Database migration alembic
cd backend/app/ # Generate migration file alembic revision --autogenerate # Execute the migration alembic upgrade head
-
Execute the
backend/app/main.py
file to start the service -
Browser access: http://127.0.0.1:8000/v1/docs
2: Docker
-
Go to the directory where the
docker-compose.yml
file is located and create the environment variable file.env
cp .env.server ../../backend/app/.env # This command is optional cp .env.docker .env
-
Execute the one-click boot command
docker-compose up -d -build
-
Wait for the command to complete automatically
-
Visit the browser: http://127.0.0.1:8000/v1/docs
Test data
Execute backend/app/init_test_data.py
file to automatically create test data
Development
Development process, for reference only
- Define the database model (model) and remember to perform database migration for each change
- Define the data validation model (schema)
- Define routes (router) and views (api)
- Define the business logic (service)
- Write database operations (crud)
Test
Execute tests via pytest
-
Create the test database
fba_test
, select utf8mb4 encoding -
Enter the app directory
cd backend/app/
-
Initialize the test data
python tests/init_test_data.py
-
Execute the test command
pytest -vs --disable-warnings
Thanks
- FastAPI
- Pydantic
- SQLAlchemy
- Casbin
- Ruff
- ......
License
This project is licensed under the terms of the MIT license