FastAPI Tutorial Part 19: OpenAPI and API Documentation
Create professional API documentation with FastAPI. Learn OpenAPI customization, Swagger UI, ReDoc, and documentation best practices.
Moshiour Rahman
Advertisement
FastAPI Auto-Documentation
FastAPI automatically generates OpenAPI documentation at:
- Swagger UI:
/docs - ReDoc:
/redoc - OpenAPI JSON:
/openapi.json
Customizing App Documentation
from fastapi import FastAPI
app = FastAPI(
title="My API",
description="""
## Overview
This API provides access to user and product data.
## Features
* User management
* Product catalog
* Order processing
""",
version="1.0.0",
terms_of_service="https://example.com/terms",
contact={
"name": "API Support",
"url": "https://example.com/support",
"email": "support@example.com"
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
)
Endpoint Documentation
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel, Field
class Item(BaseModel):
name: str = Field(
example="Widget",
description="The name of the item"
)
price: float = Field(
gt=0,
example=29.99,
description="Price in USD"
)
class Config:
json_schema_extra = {
"example": {
"name": "Premium Widget",
"price": 49.99
}
}
@app.post(
"/items",
response_model=Item,
summary="Create an item",
description="Create a new item with name and price.",
response_description="The created item",
tags=["Items"],
status_code=201
)
def create_item(item: Item):
"""
Create an item with all the information:
- **name**: required, unique name
- **price**: required, must be positive
"""
return item
Tags and Grouping
tags_metadata = [
{
"name": "Users",
"description": "User management operations"
},
{
"name": "Items",
"description": "Item CRUD operations"
}
]
app = FastAPI(openapi_tags=tags_metadata)
@app.get("/users", tags=["Users"])
def list_users():
pass
@app.get("/items", tags=["Items"])
def list_items():
pass
Response Examples
@app.get(
"/items/{item_id}",
responses={
200: {
"description": "Item found",
"content": {
"application/json": {
"example": {"id": 1, "name": "Widget", "price": 9.99}
}
}
},
404: {
"description": "Item not found",
"content": {
"application/json": {
"example": {"detail": "Item not found"}
}
}
}
}
)
def get_item(item_id: int):
pass
Hiding Endpoints
# Hide from documentation
@app.get("/internal", include_in_schema=False)
def internal_endpoint():
return {"internal": True}
# Disable docs in production
app = FastAPI(
docs_url=None if PRODUCTION else "/docs",
redoc_url=None if PRODUCTION else "/redoc"
)
Custom OpenAPI Schema
from fastapi.openapi.utils import get_openapi
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Custom API",
version="1.0.0",
description="Custom description",
routes=app.routes
)
# Add custom fields
openapi_schema["info"]["x-logo"] = {
"url": "https://example.com/logo.png"
}
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
Summary
| Feature | Method |
|---|---|
| App metadata | FastAPI() parameters |
| Endpoint docs | Decorator parameters |
| Examples | Pydantic Field() |
| Grouping | Tags |
| Custom schema | Override openapi() |
Next Steps
In Part 20, we’ll build a Complete Production API Project - putting everything together.
Series Navigation:
- Part 1-18: Previous parts
- Part 19: OpenAPI & Documentation (You are here)
- Part 20: Full Production Project
Advertisement
Moshiour Rahman
Software Architect & AI Engineer
Enterprise software architect with deep expertise in financial systems, distributed architecture, and AI-powered applications. Building large-scale systems at Fortune 500 companies. Specializing in LLM orchestration, multi-agent systems, and cloud-native solutions. I share battle-tested patterns from real enterprise projects.
Related Articles
FastAPI Tutorial Part 14: File Uploads and Storage
Handle file uploads in FastAPI. Learn form data, file validation, cloud storage integration with S3, and serving static files.
PythonFastAPI Tutorial Part 11: Background Tasks and Celery
Handle long-running operations in FastAPI. Learn built-in BackgroundTasks, Celery integration, task queues, and async processing patterns.
PythonFastAPI Tutorial Part 7: CRUD Operations - Build a Complete REST API
Build production-ready CRUD APIs with FastAPI. Learn RESTful patterns, pagination, filtering, bulk operations, and best practices for real-world applications.
Comments
Comments are powered by GitHub Discussions.
Configure Giscus at giscus.app to enable comments.