0
0
FastapiHow-ToBeginner · 3 min read

How to Include Router in FastAPI: Simple Guide

In FastAPI, you include a router by creating an APIRouter instance and then adding it to your main FastAPI app using include_router(). This helps organize your API endpoints into separate modules for cleaner code.
📐

Syntax

To include a router in FastAPI, first create an APIRouter object. Define your routes on this router. Then, use the include_router() method on your main FastAPI app to add the router.

Parts explained:

  • APIRouter(): Creates a router to hold related routes.
  • @router.get(): Decorator to define GET endpoints on the router.
  • app.include_router(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)
💻

Example

This example shows how to create a router with a simple endpoint and include it in the main FastAPI app. When you run this app and visit /items, it returns a JSON list of items.

python
from fastapi import FastAPI, APIRouter

router = APIRouter()

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

app = FastAPI()
app.include_router(router)

# To run: uvicorn filename:app --reload
Output
GET /items Response: [{"item_id": "foo"}, {"item_id": "bar"}]
⚠️

Common Pitfalls

Common mistakes when including routers in FastAPI include:

  • Forgetting to call include_router() on the main app, so routes don’t register.
  • Defining routes directly on FastAPI but expecting router behavior.
  • Using the same path prefix in multiple routers without proper prefixes, causing route conflicts.
  • Not importing the router correctly before including it.

Always ensure routers are included properly and paths are unique or prefixed.

python
from fastapi import FastAPI, APIRouter

# Wrong: router created but not included
router = APIRouter()

@router.get("/users")
async def get_users():
    return ["user1", "user2"]

app = FastAPI()
# Missing: app.include_router(router)  # This causes routes to not work

# Correct way:
app.include_router(router, prefix="/api")
📊

Quick Reference

MethodDescription
APIRouter()Create a new router to group routes
@router.get(path)Define GET endpoint on router
app.include_router(router)Add router routes to main FastAPI app
app.include_router(router, prefix='/prefix')Add router with URL prefix
app.include_router(router, tags=['tag'])Add tags for documentation

Key Takeaways

Use APIRouter to organize routes into separate modules.
Include routers in the main FastAPI app with include_router().
Use prefixes to avoid route conflicts between routers.
Always import and include routers properly to register routes.
Routers help keep your API code clean and modular.