Comments (# and """ """)
How to write comments in FastAPI. You can use Python's # (single-line comment) and triple-quoted strings ("""...""") as docstrings. In FastAPI, docstrings play a special role: writing a docstring on a path operation function (a route function decorated with @app.get() etc.) causes FastAPI to include it in the auto-generated OpenAPI documentation (Swagger UI and ReDoc).
Syntax
# Python: single-line comment — everything from # to the end of the line is a comment.
# Write above the code or at the end of a line.
"""
Python: docstring — a string literal enclosed in triple quotes.
When placed at the start of a function, class, or module it acts as documentation.
"""
@app.get("/items/{item_id}")
async def get_item(item_id: int):
"""
The docstring of a path operation function appears in the OpenAPI documentation.
This text is automatically reflected in the "Description" field of Swagger UI and ReDoc.
Markdown syntax is supported.
"""
...
Comment Types
| Type | Syntax | Description |
|---|---|---|
| Single-line comment | # text | Used throughout Python files. Everything from # to the end of the line becomes a comment. |
| Block comment | Consecutive # lines | For multi-line explanations, put # at the start of each line. Python has no dedicated multi-line comment syntax like C's /* */. |
| Docstring | """text""" | A documentation string placed immediately after a function, class, or module definition. In FastAPI, the docstring of a path operation function is automatically reflected in the OpenAPI description. |
| Module docstring | """text""" at the top of a file | When placed at the very start of a Python file, it serves as the module's documentation. In FastAPI apps, the main.py sometimes starts with a description of the application. |
The Role of Docstrings in FastAPI
In FastAPI, the docstring of a path operation function (a function decorated with @app.get() etc.) is automatically incorporated into the OpenAPI documentation.
| Location | Where the docstring appears |
|---|---|
| Path operation function (first line) | Displayed in the "Summary" field of Swagger UI and ReDoc. |
| Path operation function (second line onward) | Displayed in the "Description" field of Swagger UI and ReDoc. Markdown is supported. |
| FastAPI instance (title / description) | Set an API-wide description with FastAPI(title="...", description="..."). Markdown is supported in description. |
| Pydantic model docstring | Reflected in the OpenAPI schema as the model's description. |
You can also set a short summary separately using the summary parameter on the decorator. When both the first line of the docstring and summary are present, summary takes priority.
When to Write Comments and When Not To
| Decision | Situation | Reason |
|---|---|---|
| Write a comment | Docstring on path operation functions | FastAPI automatically reflects it in the OpenAPI documentation. API clients and collaborators can understand the endpoint specification just by looking at Swagger UI. |
| Write a comment | The reason why something was implemented a certain way | Design decisions, references to external specifications, and trade-offs left in comments help your future self and other developers. |
| Write a comment | Complex async logic or dependency chains | Adding notes about the intent of Depends() chains and background tasks makes the code easier to follow. |
| No comment needed | Logic that is obvious from reading the code | Self-evident comments become noise. Clear variable and function names remove the need for such comments. |
| No comment needed | Change history or deleted code | Because version control (git) is available, there is no need to keep old code or change dates in comments. |
Sample Code
How the docstring of a path operation function appears in Swagger UI.
main.py
# main.py — entry point for the FastAPI application.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
# Create the FastAPI instance.
# Writing Markdown in description shows it as the API-wide description in Swagger UI.
app = FastAPI(
title="Product API",
description="""
Product management API.
## Endpoint overview
- **GET /products** — Returns the product list.
- **GET /products/{product_id}** — Returns product details.
- **POST /products** — Creates a new product.
""",
version="1.0.0",
)
# Product data (a real app would use a database)
_products = [
{"id": 1, "name": "item_a", "price": 1000},
{"id": 2, "name": "item_b", "price": 2500},
]
class ProductCreate(BaseModel):
"""
Request body for creating a product.
Attributes:
name: Product name (1 to 100 characters).
price: Price (integer, 0 or greater).
"""
name: str
price: int
@app.get("/products", tags=["products"])
async def list_products():
"""
Returns the product list.
Returns the ID, name, and price of all registered products.
"""
# TODO: add pagination later.
return _products
@app.get("/products/{product_id}", tags=["products"])
async def get_product(product_id: int):
"""
Returns product details.
- **product_id**: ID of the product to retrieve.
- Returns 404 if the specified ID does not exist.
"""
# Linear search for a product matching product_id.
# Switch to an index-based implementation for large datasets.
product = next((p for p in _products if p["id"] == product_id), None)
if product is None:
raise HTTPException(status_code=404, detail="product not found")
return product
@app.post("/products", status_code=201, tags=["products"])
async def create_product(body: ProductCreate):
"""
Creates a new product.
Send name and price in the request body as JSON.
Returns the created product data.
"""
# Assign a new ID as the current maximum ID + 1.
new_id = max(p["id"] for p in _products) + 1 if _products else 1
new_product = {"id": new_id, "name": body.name, "price": body.price}
_products.append(new_product)
return new_product
Opening Swagger UI at http://localhost:8000/docs shows the docstring content automatically in the "Summary" and "Description" fields. Markdown formatting such as bold (**) and bullet points (-) is rendered as-is.
Common Mistakes
Duplicate content between the docstring first line and summary
When the summary parameter is specified on the decorator, it takes priority over the first line of the docstring for the "Summary" field in Swagger UI. If both are present, the unintended one may be displayed.
# Both summary and the docstring first line are present
@app.get("/items", summary="Returns the item list")
async def list_items():
"""
Returns the item list. # ← Not shown in Summary (summary parameter takes priority)
Detailed description goes here.
"""
...
Assuming # comments in the function body affect OpenAPI
Only docstrings (triple-quoted strings) are reflected in the OpenAPI documentation. A # comment inside a function is a regular Python comment and has no effect on the OpenAPI output whatsoever.
@app.get("/items")
async def list_items():
"""This string appears in OpenAPI."""
# This # comment does not appear in OpenAPI.
return []
Overview
FastAPI supports Python's standard comment syntax: # and docstrings. Of these, docstrings are directly tied to a key FastAPI feature. Writing a docstring on a path operation function causes FastAPI to automatically include it in the generated OpenAPI documentation (Swagger UI and ReDoc). The first line of the docstring maps to "Summary" and subsequent lines map to "Description", with Markdown supported.
Docstrings on Pydantic models are also reflected in the OpenAPI schema as model descriptions. Writing docstrings on path operation functions and key Pydantic models is common practice so that API consumers can understand the specification just by reading Swagger UI.
If you find any errors or copyright issues, please contact us.