How to Add Tags to Endpoints in FastAPI for Better API Docs
In FastAPI, you add tags to endpoints by using the
tags parameter in the route decorator like @app.get('/path', tags=['tag1']). These tags help group endpoints in the automatic API docs for easier navigation.Syntax
Use the tags parameter inside the route decorator to assign one or more tags to an endpoint. Tags are passed as a list of strings.
@app.get('/path', tags=['tag1', 'tag2']): Assigns tags to a GET endpoint.@app.post('/path', tags=['tag']): Assigns tags to a POST endpoint.
python
@app.get('/items/', tags=['items']) async def read_items(): return [{'item_id': 'foo'}]
Example
This example shows how to add tags to multiple endpoints to organize them in the FastAPI automatic docs. Tags group endpoints under named sections.
python
from fastapi import FastAPI app = FastAPI() @app.get('/users/', tags=['users']) async def get_users(): return [{'username': 'alice'}, {'username': 'bob'}] @app.post('/users/', tags=['users']) async def create_user(name: str): return {'username': name} @app.get('/items/', tags=['items']) async def get_items(): return [{'item_id': 'item1'}, {'item_id': 'item2'}]
Output
Running this app and opening /docs shows two groups: 'users' and 'items', each with their endpoints listed.
Common Pitfalls
Common mistakes when adding tags include:
- Not passing tags as a list of strings, e.g.,
tags='users'instead oftags=['users']. - Forgetting to add tags to all related endpoints, which leads to inconsistent grouping.
- Using too many or unclear tags, which can clutter the docs.
python
from fastapi import FastAPI app = FastAPI() # Wrong: tags should be a list @app.get('/wrong', tags='wrong') async def wrong_tag(): return {'msg': 'This will cause an error'} # Right @app.get('/right', tags=['right']) async def right_tag(): return {'msg': 'This works fine'}
Quick Reference
Summary tips for adding tags in FastAPI:
- Always use a list of strings for
tags. - Use meaningful tag names that describe endpoint groups.
- Consistently tag all endpoints in the same group.
- Tags improve API docs navigation and readability.
Key Takeaways
Add tags to FastAPI endpoints using the tags parameter as a list of strings.
Tags group endpoints in the automatic API docs for better organization.
Always use consistent and meaningful tag names across related endpoints.
Passing tags as a string instead of a list causes errors.
Tags improve the user experience when exploring your API documentation.