FastAPI 怎样从代码生成 API 文档?
查看完整题解
参考回答
直接回答
FastAPI 从路由、参数、模型、安全声明和元数据生成 OpenAPI JSON。Swagger UI、ReDoc 等页面读取这份描述,对调用方呈现接口。
讲清原理
自动生成能减少手工抄文档,但业务错误、示例和权限语义仍要按需补充。重要版本应测试 schema 与真实响应一致。
例子与易错点
示例在测试进程读取 /openapi.json,核对字段结构和路径。这可以防止改路由以后文档仍指向旧地址。
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
class Item(BaseModel):
title: str = Field(min_length=1)
app = FastAPI(title="Catalog")
@app.post("/items", status_code=201, response_model=Item)
def create_item(item: Item):
return item
with TestClient(app) as client:
spec = client.get("/openapi.json").json()
operation = spec["paths"]["/items"]["post"]
assert "201" in operation["responses"]
item_schema = spec["components"]["schemas"]["Item"]
assert item_schema["required"] == ["title"] and item_schema["properties"]["title"]["minLength"] == 1
assert client.post("/items", json={"title": "Tea"}).status_code == 201
print("OpenAPI and route both report 201")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。