This project serves as a starting structure (boilerplate/template) for developing resilient, high-performance, and scalable web applications and REST APIs with FastAPI. It implements a strict separation of responsibilities (Clean Architecture) and rigorous typing at all levels.
This repository is configured as a GitHub Template Repository. You can create a new repository from this template with one click:
- Click "Use this template" on GitHub
- Select "Create a new repository"
- Clone your new repository and you're ready to go!
π Documentation Available in Other Languages
To deeply understand the different components of the application and recommended patterns, please refer to the following documents:
- π Architecture Overview & Data Flow - EN / FR : Conceptual model (Router β Service β Repository β Cache) and lifecycle.
- π Database & Models - EN / FR : SQLAlchemy 2.0,
IntegrityMapperMixinmixin, and constraint management. - π Results & Errors Management - EN / FR :
GenericAppResultreturn model and subclasses (CrudResult,ServiceResult,IntegrationServiceResult). - π Cache System - EN / FR : Type-safe Redis cache registration and usage via Factory.
- π Authentication & Security (RBAC) - EN / FR : Dual cookie (Access/Refresh),
HttpOnlyauthentication, and role dependencies. - π Repositories & Services - EN / FR : Data and business logic modules writing and structuring.
- π API Routers & Middlewares - EN / FR : Premium Swagger configuration, Pydantic validation, and diagnostic middlewares.
When adding a new entity to the application (e.g., a Product), you must follow this step-by-step cycle to respect the template paradigm:
graph TD
A[1. Database Model & Constraints] --> B[2. Import tables & Alembic Migration]
B --> C[3. Pydantic Schemas]
C --> D[4. Repository & CRUD]
D --> E[5. Cache Keys Definition & Cacher]
E --> F[6. Business Service]
F --> G[7. Router & API Registration]
Create the model file in app/db/models/product.py.
- Inherit from
Base(which integratesMappedAsDataclass) andIntegrityMapperMixin. - Define all table constraints (uniques, foreign keys, checks) as explicit constants at the top of the file.
- Fill in the
ERROR_MESSAGESdictionary mapping SQL constraints to user error messages. - For automatic columns (ID, timestamps, relationships), use
init=False.
- Import your model within the
add_all_tables()function in app/db/init.py so Alembic can detect it:def add_all_tables(): from app.db.models.user import User from app.db.models.session import Session from app.db.models.product import Product # <-- IMPORT
- Generate the SQL migration file:
alembic revision --autogenerate -m "Create product table" - Apply the migration to your local database:
alembic upgrade head
In the app/schemas/ folder, create product_schemas.py:
- Create request schemas (e.g.,
CreateProduct,UpdateProduct). - Create the typed output schema (e.g.,
ReadProductwithfrom_attributes = True). - Create the API response wrapper by inheriting from
DefaultAppApiResponse(e.g.,ProductInfos(DefaultAppApiResponse[ReadProduct])) for premium Swagger documentation.
Create the repository file in app/repositories/product_repository.py.
- Declare a class decorated with
@dataclassreceivingdb: AsyncSession. - Implement CRUD methods by wrapping queries in a
try/exceptblock. - Intercept errors by redirecting exceptions to
RepositoriesUtils.traiter_errors_en_globalpassing the entity model. - Always return a
CrudResultobject (orDefaultAppCrudResult).
- Define the cache key pattern in
BaseCacheEntityandAvailableCacheKeys(in app/cache/helpers/availables.py). - Declare the key in
CacheKeysFactory(in app/cache/helpers/keys_factory.py) with its number of placeholders. - Create a dedicated cache class
ProductCacheinapp/cache/product_cache.pyto isolate Redis accesses.
Create the service file in app/services/product_service.py.
- Take
db: AsyncSessionandcache: CacheWrapperin the__init__constructor. - Internally instantiate
ProductRepositoryandProductCache. - Implement business logic: read cache first, query repository on cache-miss, save read data in cache, and return a
ServiceResult(orDefaultAppServiceResult). - Propagate repository failures to the service via
repo_res.to_service_error(service_name=self._service_name).
Create the router file in app/routers/v1/product_router.py.
- Create the
APIRouterinstance with appropriate tags. - Inject the service with
Depends(get_product_service). - Set the route's
response_modelto your concrete wrapper (e.g.,response_model=ProductInfos). - Specify the return annotation
-> ApiBaseResponse[ReadProduct, AppError]. - Register the new router in the main router app/routers/v1/base_router.py via
v1_api_router.include_router(product_router).
- Python 3.11+
- PostgreSQL database (or Dockerized)
- Redis (for cache and Celery)
- Clone the project and prepare the environment:
python -m venv .venv source .venv/bin/activate pip install -r requirements.txt - Configure environment variables:
Copy the
.env.examplefile to.envand adjust the PostgreSQL and Redis access parameters. - Run database migrations:
alembic upgrade head
- Start the development server:
# Uses uvicorn under the hood to run the application on the configured port python app/main.py - Access API documentation: Open your browser to http://localhost:8000/docs to view the interactive Swagger.
If your project uses Celery for asynchronous processing, start the Celery worker from the project root:
celery -A app.worker.celery_app worker --loglevel=infoThis project includes a complete Docker configuration that is operational and ready to use out of the box. The setup is designed for immediate use - just copy, paste, and run!
The docker-compose.yml file provides a complete development environment with:
- PostgreSQL 15 (Alpine) - Database service with health checks
- Redis 7 (Alpine) - Cache and message broker with persistence
- FastAPI Backend - Main application server with auto-reload
- Celery Worker - Background task processing (commented out by default)
All services include:
- β Health checks for automatic dependency management
- β Volume persistence for data
- β Automatic restart on failure
- β Service dependencies (API waits for DB and Redis to be healthy)
The .env.example file contains a ready-to-use configuration:
ENVIRONMENT=LOCAL
DATABASE_USER=admin
DATABASE_PASSWORD=password
DATABASE_TYPE=postgresql
DATABASE_PILOT=asyncpg
DATABASE_HOST=db:5432
BD_OUTPUT_PORT=5433
DATABASE_NAME=app_db
SECRET_KEY=change-me
API_PORT=8000
REDIS_CACHE_PORT=6379
REDIS_URL=redis://app_redis:6379/0This configuration is fully operational with the provided docker-compose.yml. Simply:
- Copy
.env.exampleto.env - Run
docker compose up -d - Your application will be available at
http://localhost:8000
The included Makefile provides convenient shortcuts for common Docker operations:
| Command | Description |
|---|---|
make build_docker |
Build Docker images |
make rebuild_docker |
Rebuild Docker images without cache |
make start_docker |
Start all services in detached mode |
make stop_docker |
Stop and remove all containers |
make restart_api |
Restart only the API service |
make migrate-up |
Run database migrations |
make migrate-down |
Rollback last migration |
make migrate-gen |
Generate new migration (use with: make migrate-gen msg="your message") |
Example workflow:
# Start everything
make start_docker
# Run migrations
make migrate-up
# Stop everything
make stop_dockerTip
The Makefile automatically handles user permissions on Linux/Mac (avoiding file ownership issues) and works seamlessly on Windows with Docker Desktop.
All documentation files in the docs/ directory are available in both English and French:
- English versions have the
_en.mdsuffix - French versions have the
_fr.mdsuffix
Each documentation file contains a notice at the top indicating the availability of the other language version.
