FastAPI project structure that incorporates multiple design patterns including:
- Dependency Injection
- Repository Pattern
- Service Layer
- Strategy Pattern
- Factory Pattern
- Observer Pattern
- Builder Pattern
- Domain-Driven Design (DDD)Β principles
π§± Project Structure
fastapi_project/
β
βββ app/
β βββ main.py # FastAPI app entry point
β βββ config.py # App configuration
β βββ dependencies/ # DI providers
β β βββ db.py
β β βββ auth.py
β β βββ __init__.py
β β
β βββ models/ # Pydantic models
β β βββ user.py
β β βββ request.py
β β βββ __init__.py
β β
β βββ domain/ # Domain models (DDD)
β β βββ entities/
β β β βββ user_entity.py
β β β βββ __init__.py
β β βββ __init__.py
β β
β βββ repositories/ # Repository pattern
β β βββ user_repository.py
β β βββ __init__.py
β β
β βββ services/ # Business logic (Service Layer)
β β βββ user_service.py
β β βββ __init__.py
β β
β βββ strategies/ # Strategy pattern
β β βββ auth/
β β β βββ jwt_strategy.py
β β β βββ oauth_strategy.py
β β β βββ __init__.py
β β βββ __init__.py
β β
β βββ factories/ # Factory pattern
β β βββ service_factory.py
β β βββ __init__.py
β β
β βββ observers/ # Observer pattern
β β βββ event_manager.py
β β βββ __init__.py
β β
β βββ builders/ # Builder pattern
β β βββ report_builder.py
β β βββ __init__.py
β β
β βββ middleware/ # Custom middleware
β β βββ logging_middleware.py
β β βββ __init__.py
β β
β βββ routes/ # API routes
β β βββ user_routes.py
β β βββ __init__.py
β β
β βββ utils/ # Utility functions
β βββ helpers.py
β βββ __init__.py
β
βββ requirements.txt
βββ README.md
π§© How Patterns Fit Together
| Pattern | Folder | Purpose |
|---|---|---|
| Dependency Injection | dependencies/ | Inject DB, auth, config |
| Repository | repositories/ | Abstract DB access |
| Service Layer | services/ | Business logic |
| Strategy | strategies/ | Pluggable auth or processing logic |
| Factory | factories/ | Create services based on config |
| Observer | observers/ | Event-driven notifications |
| Builder | builders/ | Construct complex objects |
| DDD | domain/ | Domain entities and aggregates |
Conclusion: In aΒ FastAPIΒ project, you can implement severalΒ software design patternsΒ to improve modularity, scalability, and maintainability. Hereβs a categorized overview of the most relevant patterns and how they apply to FastAPI
