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
Leave a comment