Separation of Concerns: Keep your API routes, business logic, data models, and database schemas separate. Routes should be thin - they handle HTTP concerns and delegate to services for business logic.
Dependency Injection: Use FastAPI's dependency system extensively. Create reusable dependencies for database sessions, authentication, pagination, etc.
Configuration Management: Use Pydantic's BaseSettings for configuration:
python
# app/config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
app_name: str = "My API"
database_url: str
secret_key: str
class Config:
env_file = ".env"
settings = Settings()
API Versioning: Structure your API with versioning in mind from the start. This makes it easier to introduce breaking changes later.
Service Layer: Put business logic in service modules, not in route handlers. This makes the logic testable and reusable:
python
# app/api/v1/endpoints/users.py
from fastapi import APIRouter, Depends
from app.services import user as user_service
router = APIRouter()
@router.post("/users")
async def create_user(user_data: UserCreate, db: Session = Depends(get_db)):
return await user_service.create_user(db, user_data)
For Larger Projects
As your project grows, consider:
Domain-Driven Structure: Organize by feature/domain instead of technical layers
CQRS Pattern: Separate read and write operations
Repository Pattern: Abstract database operations
Background Tasks: Use Celery or FastAPI's background tasks for async operations
Caching: Implement Redis for caching frequently accessed data
API Gateway: Consider using Kong or similar for microservices
The key is starting simple and refactoring as needed. FastAPI's flexibility allows you to evolve your structure as requirements change.