0
0
FastapiHow-ToBeginner · 3 min read

How to Use APIRouter in FastAPI for Modular APIs

Use APIRouter in FastAPI to group related routes into separate modules. Create an APIRouter instance, define routes on it, then include it in the main FastAPI app with include_router().
📐

Syntax

The APIRouter class lets you create a router object to hold routes. You define routes on this router just like on the main app. Then you add the router to your main FastAPI app using include_router().

  • router = APIRouter(): creates a new router instance.
  • @router.get("/path"): defines a GET route on the router.
  • app.include_router(router, prefix="/prefix"): adds the router to the main app with an optional URL prefix.
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 create an APIRouter for item-related routes and include it in the main FastAPI app with a prefix. The app will respond to /api/items with a JSON list.

python
from fastapi import FastAPI, APIRouter

router = APIRouter()

@router.get("/items")
async def get_items():
    return [{"item_id": "foo"}, {"item_id": "bar"}]

app = FastAPI()
app.include_router(router, prefix="/api")
Output
GET /api/items Response: [{"item_id": "foo"}, {"item_id": "bar"}]
⚠️

Common Pitfalls

Common mistakes when using APIRouter include:

  • Forgetting to include the router in the main app with include_router(), so routes don’t work.
  • Not using a prefix when needed, causing route conflicts.
  • Defining routes on the main app instead of the router, losing modularity benefits.

Always create routes on the router instance and then add it to the app.

python
from fastapi import FastAPI, APIRouter

router = APIRouter()

# Wrong: defining route on app instead of router
app = FastAPI()

@app.get("/items")  # This is not modular
async def get_items():
    return [{"item_id": "foo"}]

# Right way:
router = APIRouter()

@router.get("/items")
async def get_items():
    return [{"item_id": "foo"}]

app.include_router(router, prefix="/api")
📊

Quick Reference

Summary tips for using APIRouter:

  • Create an APIRouter() instance for related routes.
  • Define routes on the router using decorators like @router.get().
  • Use app.include_router(router, prefix="/prefix") to add routes to the main app.
  • Use prefixes to avoid route conflicts and organize URLs.
  • Keep your API modular and easier to maintain by splitting routes into multiple routers.

Key Takeaways

Use APIRouter to group related routes for cleaner, modular FastAPI apps.
Define routes on the APIRouter instance, not directly on the main app.
Include routers in the main app with include_router() and use prefixes to organize paths.
Forgetting to include the router or missing prefixes can cause route conflicts or missing endpoints.
Modular routing improves code organization and scalability in FastAPI projects.