Fast API Project Structure

14 Aug

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

PatternFolderPurpose
Dependency Injectiondependencies/Inject DB, auth, config
Repositoryrepositories/Abstract DB access
Service Layerservices/Business logic
Strategystrategies/Pluggable auth or processing logic
Factoryfactories/Create services based on config
Observerobservers/Event-driven notifications
Builderbuilders/Construct complex objects
DDDdomain/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