0
0
FastAPIframework~5 mins

APIRouter for modular routes in FastAPI

Choose your learning style9 modes available
Introduction

APIRouter helps you organize your web app by splitting routes into smaller parts. This makes your code cleaner and easier to manage.

When your app has many routes and you want to keep them in separate files.
When different parts of your app have different groups of routes, like users and products.
When you want to reuse route groups in multiple apps.
When you want to keep your main app file simple and tidy.
Syntax
FastAPI
from fastapi import APIRouter

router = APIRouter()

@router.get("/path")
async def some_route():
    return {"message": "Hello from router"}

# In main app file
from fastapi import FastAPI
from your_router_file import router

app = FastAPI()
app.include_router(router, prefix="/prefix")

Use APIRouter() to create a router object.

Use app.include_router() to add the router to your main app.

Examples
This creates a router with a GET route at /items.
FastAPI
from fastapi import APIRouter

router = APIRouter()

@router.get("/items")
async def read_items():
    return ["item1", "item2"]
This adds the router to the main app with the prefix /api, so the route becomes /api/items.
FastAPI
app.include_router(router, prefix="/api")
You can add tags to group routes for documentation.
FastAPI
router = APIRouter(tags=["users"])

@router.post("/users")
async def create_user():
    return {"user": "created"}
Sample Program

This example shows a user router with GET and POST routes. The router is added to the main app with prefix /api, so the full paths are /api/users.

FastAPI
from fastapi import FastAPI, APIRouter

# Create a router for user routes
user_router = APIRouter()

@user_router.get("/users")
async def get_users():
    return [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]

@user_router.post("/users")
async def create_user(name: str):
    return {"id": 3, "name": name}

# Main app
app = FastAPI()
app.include_router(user_router, prefix="/api")
OutputSuccess
Important Notes

Use prefixes to avoid route name conflicts.

Routers help keep your code organized as your app grows.

You can add tags to routers for better API docs grouping.

Summary

APIRouter lets you split routes into smaller, manageable parts.

Include routers in your main app with include_router() and optional prefixes.

This keeps your FastAPI app clean and easier to maintain.