8. Scalable FastAPI Project Structure
As your API grows from a few endpoints to dozens or hundreds, how you organize your code becomes critical. A well-structured project is easy to navigate, test, and maintain. This module covers professional project structures that scale from small projects to enterprise applications. To implement these structures, create the folders and files locally following the patterns below.
The Flat Structure (Small Projects)
For very small APIs with 5-10 endpoints, a flat structure in a single file is acceptable. But beware — this does not scale.
my-api/ ├── main.py # All endpoints, models, and logic ├── requirements.txt └── .env
The Modular Structure (Recommended)
For most production applications, use a modular structure that separates code by feature or domain. This is the industry standard for FastAPI projects.
my-api/ ├── app/ │ ├── __init__.py │ ├── main.py # FastAPI app creation │ ├── config.py # Settings │ ├── database.py # DB connection │ ├── api/ │ │ ├── __init__.py │ │ ├── dependencies.py │ │ └── v1/ │ │ ├── endpoints/ │ │ │ ├── users.py │ │ │ └── products.py │ │ └── models/ │ ├── core/ │ │ ├── security.py │ │ └── exceptions.py │ ├── crud/ │ │ └── user.py │ ├── models/ │ │ └── user.py │ └── schemas/ │ └── user.py ├── tests/ ├── .env └── requirements.txt
Setting Up the Main Application
The main.py file creates the FastAPI app, configures middleware, includes routers, and sets up exception handlers.
# app/main.py from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.config import settings from app.api.v1.endpoints import users, products def create_application() -> FastAPI: app = FastAPI(title=settings.PROJECT_NAME, version=settings.VERSION) app.add_middleware( CORSMiddleware, allow_origins=settings.BACKEND_CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(users.router, prefix="/api/v1/users", tags=["users"]) app.include_router(products.router, prefix="/api/v1/products", tags=["products"]) @app.get("/health") async def health_check(): return {"status": "healthy"} return app app = create_application()
Router Organization (Endpoints)
Each router file contains endpoints for a specific resource. Keep routers focused on request/response handling; delegate business logic to services or CRUD modules.
# app/api/v1/endpoints/users.py from fastapi import APIRouter, Depends, HTTPException, status from typing import List from app.schemas.user import UserCreate, UserResponse from app.crud.user import crud_user from app.api.dependencies import get_current_user router = APIRouter() @router.get("/", response_model=List[UserResponse]) async def get_users(skip: int = 0, limit: int = 100): users = await crud_user.get_multi(skip=skip, limit=limit) return users @router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED) async def create_user(user_in: UserCreate): user = await crud_user.create(obj_in=user_in) return user @router.get("/{user_id}", response_model=UserResponse) async def get_user(user_id: int): user = await crud_user.get(id=user_id) if not user: raise HTTPException(status_code=404, detail="User not found") return user @router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_user(user_id: int): if not await crud_user.remove(id=user_id): raise HTTPException(status_code=404, detail="User not found") return None
Pydantic Schemas (Request/Response Models)
Keep your Pydantic schemas in separate files. Use different schemas for different operations (create, update, response).
# app/schemas/user.py from pydantic import BaseModel, EmailStr, Field from datetime import datetime from typing import Optional class UserBase(BaseModel): email: EmailStr is_active: bool = True class UserCreate(UserBase): password: str = Field(..., min_length=8) name: str = Field(..., min_length=1, max_length=50) class UserUpdate(BaseModel): email: Optional[EmailStr] = None name: Optional[str] = None password: Optional[str] = None class UserResponse(UserBase): id: int name: str created_at: datetime class Config: from_attributes = True
Configuration Management
Use Pydantic Settings for environment-based configuration. This keeps secrets out of your code and makes deployment easy.
# app/config.py from pydantic_settings import BaseSettings from typing import List class Settings(BaseSettings): PROJECT_NAME: str = "My FastAPI App" VERSION: str = "1.0.0" API_V1_STR: str = "/api/v1" DEBUG: bool = False SECRET_KEY: str ALGORITHM: str = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 DATABASE_URL: str BACKEND_CORS_ORIGINS: List[str] = ["http://localhost:3000"] class Config: env_file = ".env" case_sensitive = True settings = Settings()
Knowledge Check
Ready to test your understanding of 8. Scalable FastAPI Project Structure?