Skip to main content

FastAPI Route Tags

When building APIs with multiple endpoints, maintaining organization becomes essential. FastAPI provides a feature called route tags that helps you categorize and group your API endpoints. Tags make your API documentation more navigable and help other developers understand the organization of your API at a glance.

Introduction to Route Tags

Tags in FastAPI serve as labels for your routes, allowing you to group related endpoints together. They appear in the automatic documentation interface, creating an organized structure that makes it easier to explore your API.

Let's see how tags work in practice.

Basic Tag Usage

To add a tag to a route, you simply include the tags parameter in your route decorator:

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/", tags=["users"])
async def get_users():
return {"users": ["John", "Jane", "Bob"]}

@app.post("/users/", tags=["users"])
async def create_user():
return {"message": "User created"}

@app.get("/items/", tags=["items"])
async def get_items():
return {"items": ["Item1", "Item2"]}

In this example, we've grouped our endpoints into two categories: users and items. When you visit the automatic documentation at /docs, you'll see these endpoints organized under their respective tag headers.

Multiple Tags

You can assign multiple tags to a single endpoint if it belongs to multiple categories:

python
@app.get("/user-items/", tags=["users", "items"])
async def get_user_items():
return {
"user-items": [
{"user": "John", "items": ["Item1", "Item2"]},
{"user": "Jane", "items": ["Item3"]}
]
}

This endpoint will appear under both the "users" and "items" sections in the documentation.

Tag Metadata

While simple tags are helpful, you can enhance your documentation by adding metadata to your tags. This allows you to provide descriptions, external documentation links, and more:

python
from fastapi import FastAPI

app = FastAPI(
openapi_tags=[
{
"name": "users",
"description": "Operations related to users",
"externalDocs": {
"description": "Users external docs",
"url": "https://example.com/users/",
},
},
{
"name": "items",
"description": "Manage items in the system",
},
]
)

@app.get("/users/", tags=["users"])
async def get_users():
return {"users": ["John", "Jane", "Bob"]}

@app.get("/items/", tags=["items"])
async def get_items():
return {"items": ["Item1", "Item2"]}

Now, in your API documentation, each tag section includes its description and any external documentation links you've provided.

Organizing Routes with Tags in Larger Applications

In real-world applications, you might have dozens or even hundreds of endpoints. Using tags strategically can greatly improve the organization of your API.

Here's a more comprehensive example of how you might organize routes in a blog platform API:

python
from fastapi import FastAPI

app = FastAPI(
openapi_tags=[
{"name": "auth", "description": "Authentication operations"},
{"name": "users", "description": "User management operations"},
{"name": "posts", "description": "Blog post operations"},
{"name": "comments", "description": "Comment operations"},
{"name": "admin", "description": "Administrative operations"},
]
)

# Authentication routes
@app.post("/login/", tags=["auth"])
async def login():
return {"message": "Login successful"}

@app.post("/register/", tags=["auth"])
async def register():
return {"message": "Registration successful"}

# User routes
@app.get("/users/", tags=["users"])
async def get_users():
return {"users": ["John", "Jane"]}

@app.get("/users/{user_id}", tags=["users"])
async def get_user(user_id: int):
return {"user_id": user_id, "name": "John Doe"}

# Post routes
@app.get("/posts/", tags=["posts"])
async def get_posts():
return {"posts": ["Post 1", "Post 2"]}

@app.post("/posts/", tags=["posts"])
async def create_post():
return {"message": "Post created"}

# Comment routes
@app.get("/posts/{post_id}/comments/", tags=["comments"])
async def get_comments(post_id: int):
return {"post_id": post_id, "comments": ["Comment 1", "Comment 2"]}

# Admin routes
@app.delete("/admin/users/{user_id}", tags=["admin", "users"])
async def delete_user(user_id: int):
return {"message": f"User {user_id} deleted"}

Practical Benefits of Using Tags

Using tags in your FastAPI application offers several important benefits:

  1. Improved Developer Experience: Developers can quickly find the endpoints they're looking for.
  2. Better Documentation: The auto-generated documentation is more organized and easier to navigate.
  3. Code Organization: Tags can mirror your application's structure, making the code more maintainable.
  4. API Evolution: As your API grows, tags help maintain organization without refactoring URLs.
  5. Permission Control: Tags can align with permission groups, making authorization logic more intuitive.

Using Tags with Router Objects

When working with larger applications, you'll likely use FastAPI's APIRouter to break your routes into separate modules. Tags work seamlessly with routers and can be applied at both the router and individual route levels:

python
from fastapi import APIRouter, FastAPI

app = FastAPI()

# Create a router with a default tag
user_router = APIRouter(
prefix="/users",
tags=["users"],
)

# All routes in this router automatically get the "users" tag
@user_router.get("/")
async def get_users():
return {"users": ["John", "Jane"]}

@user_router.get("/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id, "name": "John Doe"}

# Individual routes can override or add tags
@user_router.delete("/{user_id}", tags=["users", "admin"])
async def delete_user(user_id: int):
return {"message": f"User {user_id} deleted"}

# Include the router in the app
app.include_router(user_router)

This approach allows you to maintain default tags for related endpoints while still providing flexibility when needed.

Summary

FastAPI's route tags provide a powerful way to organize your API endpoints. Using tags effectively results in more navigable documentation, clearer code structure, and a better developer experience. Key points to remember:

  • Tags group related endpoints in documentation
  • You can assign multiple tags to a single endpoint
  • Tag metadata enhances documentation with descriptions and external links
  • Tags work seamlessly with APIRouter objects
  • Strategic tag planning makes APIs more maintainable as they grow

Exercises

  1. Create a simple REST API for a library system with appropriate tags for books, members, and loans.
  2. Add metadata to your tags including descriptions and external documentation links.
  3. Implement the same API using APIRouter objects with default tags.
  4. Try creating a route that belongs to multiple categories and assign it multiple tags.
  5. Explore the Swagger UI documentation for your API and see how tags affect the organization.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)