使用 Swagger UI 构建交互式 API 文档
探索 FastAPI 自动生成的交互式文档,使用元数据和标签进行定制,并直接在浏览器中用它测试端点。
使用 Swagger UI 构建交互式 API 文档 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Docs for Free
FastAPI's standout perk: automatic interactive docs. From your type hints and models it builds an OpenAPI schema and serves Swagger UI at /docs and ReDoc at /redoc.
Where Docs Come From
Both doc UIs render one OpenAPI JSON spec that FastAPI builds from your routes, params, and models. View the raw spec at /openapi.json.
App-Level Metadata
Pass app metadata — title, description, version — to the FastAPI constructor to brand your docs.
from fastapi import FastAPI
app = FastAPI(
title='Bookstore API',
description='Manage books and orders',
version='1.0.0',
)Summaries and Descriptions
Give each route a summary plus a docstring. The docstring becomes the long description in the docs and even supports Markdown.
@app.get('/books', summary='List all books')
async def list_books():
"""Return **every** book in the catalog."""
return booksGrouping with Tags
Use tags to group related endpoints into collapsible sections, keeping large APIs tidy in the docs.
@app.get('/users', tags=['users'])
async def list_users():
return users
@app.get('/books', tags=['books'])
async def list_books():
return booksDocumenting Responses
Declare alternate responses with the responses parameter so the docs list every status code a client might get, like a 404.
@app.get('/books/{id}', responses={404: {'description': 'Book not found'}})
async def get_book(id: int):
return books[id]Example Values
Add examples via Pydantic Field so Swagger UI pre-fills realistic values, making Try it out far easier.
from pydantic import BaseModel, Field
class Book(BaseModel):
title: str = Field(examples=['Dune'])
pages: int = Field(examples=[412])Building OpenAPI Mentally
The OpenAPI schema is just structured data. Here is a tiny Python sketch of grouping routes by tag to make that concrete.
routes = [
{'path': '/users', 'tag': 'users'},
{'path': '/books', 'tag': 'books'},
{'path': '/orders', 'tag': 'books'},
]
grouped = {}
for r in routes:
grouped.setdefault(r['tag'], []).append(r['path'])
print(grouped)Try It Out
In Swagger UI, hit Try it out, fill params, and Execute. You get a real request, the curl command, and the live response — no client code needed.
Customizing or Disabling Docs
Change the doc URLs or disable docs entirely (handy for production) right from constructor arguments.
app = FastAPI(docs_url='/api-docs', redoc_url=None)
# Disable both:
# app = FastAPI(docs_url=None, redoc_url=None)Why It Matters
Because docs are generated from your code, they stay accurate and never drift like handwritten ones — cutting friction for frontend teams and API consumers.
Quick Check
Where does FastAPI get the information it uses to build the interactive docs?
Recap
You explored FastAPI's automatic docs: Swagger and ReDoc from the OpenAPI spec, metadata, tags and examples, and how to customize or disable them.
常见问题解答
「使用 Swagger UI 构建交互式 API 文档」课时是免费的吗?
是的 — 「使用 Swagger UI 构建交互式 API 文档」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
「使用 Swagger UI 构建交互式 API 文档」这节课中我会学到什么?
探索 FastAPI 自动生成的交互式文档,使用元数据和标签进行定制,并直接在浏览器中用它测试端点。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 FastAPI Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 Swagger UI 构建交互式 API 文档」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- FastAPI 简介与设置
- 您的第一个 API 端点
- 路径参数与查询参数
- 使用 Swagger UI 构建交互式 API 文档