How to Organize FastAPI Project for Clean and Scalable Code
To organize a
FastAPI project, separate your code into folders like app for main logic, routers for API routes, models for data schemas, and core for settings. Use APIRouter to modularize routes and keep configuration in a config.py file for clarity and scalability.Syntax
A typical FastAPI project uses these parts:
- app/main.py: The entry point creating the FastAPI app.
- app/routers/: Folder holding route files using
APIRouter. - app/models/: Data models and schemas with Pydantic.
- app/core/: Configuration and settings.
- app/utils/: Helper functions.
This structure keeps code clean and easy to maintain.
python
from fastapi import FastAPI from app.routers import items app = FastAPI() app.include_router(items.router, prefix="/items", tags=["items"]) @app.get("/") async def root(): return {"message": "Hello World"}
Example
This example shows a small FastAPI project with organized folders and routers.
plaintext
app/
├── main.py
├── routers/
│ └── items.py
├── models/
│ └── item.py
└── core/
└── config.py
# app/main.py
from fastapi import FastAPI
from app.routers import items
app = FastAPI()
app.include_router(items.router, prefix="/items", tags=["items"])
@app.get("/")
async def read_root():
return {"message": "Welcome to FastAPI organized project"}
# app/routers/items.py
from fastapi import APIRouter
from app.models.item import Item
router = APIRouter()
@router.get("/", response_model=list[Item])
async def get_items():
return [{"id": 1, "name": "Item One"}, {"id": 2, "name": "Item Two"}]
# app/models/item.py
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
# app/core/config.py
class Settings:
app_name: str = "FastAPI Project"
admin_email: str = "admin@example.com"
settings = Settings()Output
GET / -> {"message": "Welcome to FastAPI organized project"}
GET /items/ -> [{"id":1,"name":"Item One"},{"id":2,"name":"Item Two"}]
Common Pitfalls
Common mistakes when organizing FastAPI projects include:
- Putting all routes in
main.py, making it hard to maintain. - Not using
APIRouter, which limits modularity. - Mixing configuration and business logic in one file.
- Ignoring environment-specific settings.
Keep routes modular, separate config, and use environment variables for settings.
python
## Wrong way: all routes in main.py from fastapi import FastAPI app = FastAPI() @app.get("/items") async def get_items(): return ["item1", "item2"] ## Right way: use APIRouter in separate file # app/routers/items.py from fastapi import APIRouter router = APIRouter() @router.get("/") async def get_items(): return ["item1", "item2"] # app/main.py from fastapi import FastAPI from app.routers.items import router app = FastAPI() app.include_router(router, prefix="/items")
Quick Reference
Tips for organizing FastAPI projects:
- Use
APIRouterfor each feature or resource. - Keep data models in
models/folder. - Store config and environment variables in
core/config.py. - Separate utility functions in
utils/. - Use descriptive folder and file names.
Key Takeaways
Organize FastAPI code into folders: app, routers, models, core, and utils for clarity.
Use APIRouter to modularize routes and keep main.py clean.
Separate configuration and environment settings from business logic.
Avoid putting all routes and logic in one file to improve maintainability.
Name files and folders clearly to reflect their purpose.