You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为FastAPI接口设置响应体示例?

解决FastAPI响应体示例位置不正确的问题

你当前用Body(examples)标注返回类型的做法有误,Body是用于配置请求体参数的工具,不能用来设置响应体示例,这才导致示例被嵌套在schema子级里。

下面是两种正确的实现方式:

方法一:通过路由responses参数定义同级示例

这种方式可以精准控制OpenAPI结构,让examples和schema处于同级位置,支持设置多个示例:

from typing import Annotated

import structlog
from fastapi import APIRouter
from pydantic import BaseModel, Field

logger = structlog.get_logger(__name__)
router = APIRouter(prefix="/ham")

class Ham(BaseModel):
    color: str = Field(..., description="What color?")

@router.get("/", responses={
    200: {
        "description": "Successful Response",
        "content": {
            "application/json": {
                "schema": {"$ref": "#/components/schemas/Ham"},
                "examples": [
                    {"color": "pink"}
                ]
            }
        }
    }
})
async def get_ham() -> Ham:
    return Ham(color="green")

生成的OpenAPI片段会符合你的要求:

"/ham/": {
  "get": {
    "summary": "Get Ham",
    "operationId": "get_ham",
    "responses": {
      "200": {
        "description": "Successful Response",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Ham"
            },
            "examples": [ 
              {
                "color": "pink"
              }
            ]
          }
        }
      }
    }
  }
}

方法二:通过Model Config设置单个示例

如果只需要单个示例,可以直接在BaseModel的配置类中定义,FastAPI会自动关联到响应结构中:

class Ham(BaseModel):
    color: str = Field(..., description="What color?")
    class Config:
        example = {"color": "pink"}

@router.get("/")
async def get_ham() -> Ham:
    return Ham(color="green")

这种方式会在schema下生成example字段,Swagger UI同样会正常显示示例内容,适合只需要单一示例的场景。

内容的提问来源于stack exchange,提问作者sixtyfootersdude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:02:03