0
0
FastAPIframework~5 mins

Router prefix and tags in FastAPI

Choose your learning style9 modes available
Introduction

Router prefix helps group related routes under a common path. Tags organize routes in the API docs for easy reading.

When you want to group user-related routes under '/users' path.
When you want to separate admin routes from public routes.
When you want to add descriptive tags to routes for better API documentation.
When building a large API with many endpoints to keep it organized.
When you want to reuse a router with a different prefix in multiple places.
Syntax
FastAPI
from fastapi import APIRouter

router = APIRouter(prefix="/prefix_path", tags=["tag1", "tag2"])

@router.get("/endpoint")
async def example():
    return {"message": "Hello"}

The prefix adds a common path before all routes in this router.

The tags list adds labels to routes for API docs grouping.

Examples
This groups user routes under '/users' and tags them as 'Users' in docs.
FastAPI
router = APIRouter(prefix="/users", tags=["Users"])

@router.get("/")
async def get_users():
    return ["Alice", "Bob"]
This router has two tags and a prefix for item-related routes.
FastAPI
router = APIRouter(prefix="/items", tags=["Items", "Inventory"])

@router.get("/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
You can also add tags directly on route decorators without prefix.
FastAPI
router = APIRouter()

@router.get("/status", tags=["Health"])
async def status():
    return {"status": "ok"}
Sample Program

This FastAPI app has two routers. One for users with prefix '/users' and tag 'Users'. Another for items with prefix '/items' and tag 'Items'. This organizes routes and API docs clearly.

FastAPI
from fastapi import FastAPI, APIRouter

app = FastAPI()

user_router = APIRouter(prefix="/users", tags=["Users"])

@user_router.get("/")
async def list_users():
    return ["Alice", "Bob"]

item_router = APIRouter(prefix="/items", tags=["Items"])

@item_router.get("/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id, "name": "Sample Item"}

app.include_router(user_router)
app.include_router(item_router)
OutputSuccess
Important Notes

Router prefixes help avoid repeating common path parts in every route.

Tags improve the auto-generated API docs readability by grouping endpoints.

You can add tags either on the router or on individual routes.

Summary

Router prefix groups routes under a shared path.

Tags label routes for better API documentation.

Using both keeps your API organized and easy to understand.