How to Create Modular Routes in FastAPI for Clean Code
In FastAPI, you create modular routes by using
APIRouter to define route groups in separate files or modules. Then, you include these routers in the main FastAPI app with include_router(), keeping your code clean and organized.Syntax
Use APIRouter() to create a router instance. Define routes on this router like you do on the main app. Then, use app.include_router(router) to add these routes to your main FastAPI app.
APIRouter(): Creates a modular route group.@router.get(),@router.post(): Define routes on the router.app.include_router(): Adds the router's routes to the main app.
python
from fastapi import FastAPI, APIRouter router = APIRouter() @router.get("/items") async def read_items(): return [{"item_id": "foo"}] app = FastAPI() app.include_router(router, prefix="/api")
Example
This example shows how to split routes into a separate module and include them in the main app. It demonstrates defining a router in items.py and including it with a prefix in main.py.
python
### items.py ### from fastapi import APIRouter router = APIRouter() @router.get("/") async def get_items(): return [{"item_id": "123", "name": "Item One"}] ### main.py ### from fastapi import FastAPI from items import router as items_router app = FastAPI() app.include_router(items_router, prefix="/items", tags=["items"]) # Run with: uvicorn main:app --reload
Output
When running and visiting http://localhost:8000/items/ you get JSON: [{"item_id": "123", "name": "Item One"}]
Common Pitfalls
Common mistakes include:
- Not using
APIRouterand defining all routes inFastAPI()app directly, which makes code messy. - Forgetting to include the router with
include_router(), so routes don’t work. - Not using prefixes, causing route conflicts.
- Not organizing routers in separate files, making maintenance hard.
python
### Wrong way (all routes in main app) ### from fastapi import FastAPI app = FastAPI() @app.get("/items") async def get_items(): return ["item1", "item2"] ### Right way (modular routes) ### from fastapi import FastAPI, APIRouter router = APIRouter() @router.get("/items") async def get_items(): return ["item1", "item2"] app = FastAPI() app.include_router(router, prefix="/api")
Quick Reference
Tips for modular routes in FastAPI:
- Use
APIRouter()to group related routes. - Place routers in separate files for clarity.
- Use
prefixininclude_router()to avoid path conflicts. - Add
tagsfor better API docs grouping. - Keep main app file clean by only including routers.
Key Takeaways
Use APIRouter to create modular route groups in FastAPI.
Include routers in the main app with include_router() and use prefixes to organize paths.
Keep route definitions in separate files for better code structure and maintenance.
Always add tags to routers for clearer API documentation.
Avoid defining all routes directly in the main FastAPI app to prevent clutter.