0
0
FastapiHow-ToBeginner · 3 min read

How to Use Tags with Router in FastAPI for API Grouping

In FastAPI, you add tags to a router by passing a list of strings to the tags parameter when creating an APIRouter. These tags group your endpoints in the automatic API docs, making them easier to navigate.
📐

Syntax

Use the tags parameter in the APIRouter constructor to assign tags to all routes in that router. Each tag is a string that groups related endpoints.

Example parts:

  • APIRouter(tags=["tag1", "tag2"]): Creates a router with tags.
  • @router.get("/path"): Defines a route under this router.
python
from fastapi import APIRouter

router = APIRouter(tags=["users", "accounts"])

@router.get("/profile")
async def read_profile():
    return {"message": "User profile"}
💻

Example

This example shows how to create two routers with different tags and include them in the main FastAPI app. The tags appear in the Swagger UI to group endpoints.

python
from fastapi import FastAPI, APIRouter

app = FastAPI()

user_router = APIRouter(tags=["users"])

@user_router.get("/users/me")
async def read_user_me():
    return {"user": "current user"}

item_router = APIRouter(tags=["items"])

@item_router.get("/items/")
async def read_items():
    return [{"item_id": "item1"}, {"item_id": "item2"}]

app.include_router(user_router)
app.include_router(item_router)
Output
When you run this app and open /docs, you will see two groups: 'users' and 'items', each showing their endpoints.
⚠️

Common Pitfalls

Common mistakes when using tags with routers include:

  • Not passing the tags parameter to APIRouter, so endpoints are ungrouped.
  • Assigning tags to individual routes instead of the router, which works but is less efficient for many routes.
  • Using inconsistent tag names across routers, which fragments the documentation.
python
from fastapi import APIRouter

# Wrong: No tags, endpoints won't be grouped
router = APIRouter()

@router.get("/no-tag")
async def no_tag_endpoint():
    return {"msg": "No tag"}

# Right: Tags assigned to router
router_with_tags = APIRouter(tags=["group1"])

@router_with_tags.get("/tagged")
async def tagged_endpoint():
    return {"msg": "Tagged"}
📊

Quick Reference

FeatureUsageEffect
APIRouter(tags=[...])Assign tags to routerGroups all router endpoints under these tags in docs
@router.get(..., tags=[...])Assign tags to single routeGroups only that endpoint under tags
app.include_router(router)Add router to appIncludes tagged endpoints in app
Consistent tag namesUse same tag names across routersKeeps docs organized and clear

Key Takeaways

Use the tags parameter in APIRouter to group endpoints easily.
Tags help organize your API docs for better readability.
Assign tags consistently to avoid fragmented documentation.
You can tag individual routes, but tagging routers is simpler for many endpoints.
Include routers in your FastAPI app to activate tagged routes.