Structuring a FastAPI project well is crucial for maintainability, scalability, and collaboration, especially as your application grows. While there’s no single “best” way, there are widely accepted patterns inspired by the structure of large Flask or Django projects. Here’s a recommended structure for a medium to large FastAPI project :
1. Project Directory Structure
code Copy code
my_fastapi_app/
│
├── app/
│ ├── __init__.py
│ ├── main.py # Entry point (FastAPI instance, app startup)
│ ├── api/ # API routers
│ │ ├── __init__.py
│ │ ├── v1/
│ │ │ ├── __init__.py
│ │ │ ├── endpoints/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── users.py
│ │ │ │ └── items.py
│ │ │ └── dependencies.py
│ │ └── v2/ # (optional, for versioning)
│ ├── core/ # Core app config, settings, security
│ │ ├── __init__.py
│ │ ├── config.py
│ │ └── security.py
│ ├── models/ # ORM models (e.g., SQLAlchemy)
│ │ ├── __init__.py
│ │ └── user.py
│ ├── schemas/ # Pydantic models (request/response)
│ │ ├── __init__.py
│ │ └── user.py
│ ├── crud/ # CRUD operations
│ │ ├── __init__.py
│ │ └── user.py
│ ├── db/ # Database session, init, migrations
│ │ ├── __init__.py
│ │ ├── base.py
│ │ └── session.py
│ ├── services/ # Business logic, integrations
│ │ ├── __init__.py
│ │ └── email.py
│ └── utils/ # Utility functions
│ ├── __init__.py
│ └── helpers.py
│
├── tests/ # Unit and integration tests
│ ├── __init__.py
│ └── test_users.py
│
├── alembic/ # (if using Alembic for migrations)
│
├── requirements.txt
├── .env
└── README.md
2. Key Principles
Separation of concerns: Keep routers, models, schemas, and business logic in separate modules.
Version your API: Use subfolders like api/v1/ for versioning.
Dependency injection: Use FastAPI’s dependency system for things like DB sessions, authentication, etc.
Configuration management: Use a config.py (possibly with Pydantic Settings ) for environment variables and settings.
Testing: Keep tests outside the main app directory.
3. Example: main.py
python Copy code
from fastapi import FastAPI
from app.api.v1.endpoints import users, items
app = FastAPI()
app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
app.include_router(items.router, prefix="/api/v1/items", tags=["items"])
4. Example: users.py (Router)
python Copy code
from fastapi import APIRouter, Depends
from app.schemas.user import User, UserCreate
from app.crud.user import get_user, create_user
router = APIRouter()
@router.post("/", response_model=User)
def create_new_user(user: UserCreate):
return create_user(user)
@router.get("/{user_id}", response_model=User)
def read_user(user_id: int):
return get_user(user_id)
5. Tips & Best Practices
6. References
Summary:
Start simple, but as your app grows, modularize by splitting routers, models, schemas, and business logic into their own files and folders. Use API versioning, dependency injection, and keep configuration and tests separate.
If you want a ready-to-use template, check out FastAPI Project Templates or fastapi-template .