FastAPI automatically generates OpenAPI documentation from your code.
Accessing the documentation
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc - OpenAPI JSON:
http://localhost:8000/openapi.json
Application metadata
from fastapi import FastAPI
app = FastAPI(
title="Task Manager API",
description="## Task Management API\n\nSupports CRUD for tasks and projects.",
version="1.0.0",
contact={
"name": "Support",
"email": "support@example.com",
},
license_info={"name": "MIT"},
)
Documenting endpoints
@app.get(
"/tasks/",
summary="List tasks",
description="Returns all tasks for the current user with pagination.",
response_description="List of tasks",
tags=["Tasks"],
)
def list_tasks():
...
Tags for grouping
from fastapi import APIRouter
tasks_router = APIRouter(prefix="/tasks", tags=["Tasks"])
projects_router = APIRouter(prefix="/projects", tags=["Projects"])
auth_router = APIRouter(prefix="/auth", tags=["Authentication"])
app.include_router(tasks_router)
app.include_router(projects_router)
app.include_router(auth_router)
Documenting models
from pydantic import BaseModel, Field
class TaskCreate(BaseModel):
title: str = Field(..., description="Task title", example="Write tests")
priority: int = Field(1, description="Priority from 1 to 3", ge=1, le=3)
status: str = Field("todo", description="Task status")
model_config = {
"json_schema_extra": {
"example": {
"title": "Write tests",
"priority": 2,
"status": "todo",
}
}
}
Disabling documentation
app = FastAPI(docs_url=None, redoc_url=None) # for production only
Authentication in Swagger
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
@app.get("/tasks/")
def list_tasks(token: str = Depends(oauth2_scheme)):
...
An “Authorize” button will appear in Swagger for entering a token.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!