How to Add Description to Endpoint in FastAPI
In FastAPI, you add a description to an endpoint by using the
description parameter inside the route decorator like @app.get(). This description appears in the automatic API docs, helping users understand the endpoint's purpose.Syntax
Use the description parameter inside the route decorator to add a textual explanation for the endpoint. This text shows up in the OpenAPI docs generated by FastAPI.
@app.get(path, description="Your description here"): Adds a description to a GET endpoint.@app.post(path, description="Your description here"): Adds a description to a POST endpoint.
python
@app.get("/items/", description="Get a list of items with details") async def read_items(): return [{"item_id": "foo"}, {"item_id": "bar"}]
Example
This example shows how to add a description to a GET endpoint. When you open the FastAPI docs (Swagger UI), the description will appear under the endpoint details.
python
from fastapi import FastAPI app = FastAPI() @app.get("/users/", description="Retrieve a list of users with their names and IDs.") async def get_users(): return [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
Output
Open http://127.0.0.1:8000/docs and see the description under the GET /users/ endpoint.
Common Pitfalls
Some common mistakes when adding descriptions:
- Not using the
descriptionparameter inside the decorator but trying to add it inside the function body. - Using
docstringalone does not show the description in the API docs. - For complex descriptions, use triple quotes and escape characters properly.
python
from fastapi import FastAPI app = FastAPI() # Wrong: description inside function, won't show in docs @app.get("/wrong/") async def wrong_desc(): description = "This won't appear in docs" return {"msg": "No description"} # Right: description in decorator @app.get("/right/", description="This will appear in docs") async def right_desc(): return {"msg": "Has description"}
Quick Reference
| Parameter | Purpose | Example |
|---|---|---|
| description | Adds text description to endpoint for API docs | @app.get("/path", description="Explain endpoint") |
| summary | Adds a short summary line for the endpoint | @app.get("/path", summary="Short summary") |
| response_description | Describes the response returned by the endpoint | @app.get("/path", response_description="A list of items") |
Key Takeaways
Add descriptions using the description parameter inside route decorators like @app.get().
Descriptions appear in FastAPI's automatic API docs (Swagger UI and ReDoc).
Do not rely on function docstrings alone for API documentation descriptions.
Use triple quotes for multi-line or complex descriptions to keep formatting clear.
You can also use summary and response_description for more detailed API docs.