FastAPI如何在Body中定义多个测试示例并解决default缺失报错
解决方案
报错根因
Body 函数的第一个位置参数是default,用于声明请求体参数的默认值。你直接传递关键字参数examples跳过了该必填位置参数,因此触发参数缺失错误。
正确代码实现
如果该请求体为必填参数,将Body的第一个位置参数设置为...(Python内置Ellipsis对象,代表参数无默认值、为必填项),再配置examples参数即可:
from fastapi import APIRouter, Body from fastapi.encoders import jsonable_encoder api_router = APIRouter() # 提前定义好符合my_schema结构的first_example、second_example my_examples = { "normal": { "summary": "some summary", "description": "some description", "value": first_example}, "also_normal": { "summary": "also_some summary", "description": "also_some description", "value": second_example }} @api_router.post("/my_endpoint", status_code=200) async def do_something(input_data: my_schema = Body(..., examples=my_examples)) -> dict: """ Description of this endpoint. """ results = my_function(jsonable_encoder(input_data)) return results
常见问题说明
- 之前设置
default=first_example仅能显示单示例的原因是:该配置仅声明了参数默认值,不会触发OpenAPI多示例规范的渲染逻辑 - Pydantic模型的
schema_extra配置确实仅支持单示例,要实现多示例只能通过Body的examples参数配置 - 修改完成后打开Swagger UI,该接口的请求体区域会出现示例下拉选择框,可切换两个预设示例,同时展示对应的摘要和描述信息
内容的提问来源于stack exchange,提问作者Rafa
相关产品推荐
相关产品推荐

