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

如何在FastAPI的Swagger文档中为GET响应添加自定义示例与Schema(无Pydantic)

不用Pydantic模型给FastAPI接口添加自定义响应Schema和示例

要解决Swagger文档里响应只显示"string"且Schema为空的问题,不用Pydantic的话,直接在路由装饰器里用responses参数手动定义OpenAPI规范的响应结构就行,具体实现步骤如下:

核心实现代码

假设你的接口路径是/ngo/{ngo_id},直接在@app.get()里配置responses参数,指定200状态码的响应Schema和示例:

from fastapi import FastAPI, Path
from fastapi import responses
import firebase_admin
from firebase_admin import firestore

app = FastAPI()
# 初始化Firestore(省略你的初始化代码)
db = firestore.client()

@app.get(
    "/ngo/{ngo_id}",
    responses={
        200: {
            "description": "成功获取NGO详情",
            "content": {
                "application/json": {
                    # 定义响应的Schema结构
                    "schema": {
                        "type": "object",
                        "properties": {
                            "id": {"type": "string"},
                            "name": {"type": "string"},
                            "mission": {"type": "string"},
                            "contact_email": {"type": "string"},
                            "website": {"type": "string"},
                            "address": {"type": "string"},
                            "created_at": {"type": "string", "format": "date-time"}
                        },
                        "required": ["id", "name", "mission"]  # 指定必填字段
                    },
                    # 设置自定义示例值
                    "example": {
                        "id": "ngo_12345",
                        "name": "绿色地球公益",
                        "mission": "守护自然生态,推动可持续发展",
                        "contact_email": "contact@greenearth.org",
                        "website": "https://greenearth.org",
                        "address": "上海市浦东新区环保大道88号",
                        "created_at": "2023-05-10T09:30:00Z"
                    }
                }
            }
        },
        404: {
            "description": "NGO不存在",
            "content": {
                "application/json": {
                    "schema": {
                        "type": "object",
                        "properties": {
                            "detail": {"type": "string"}
                        }
                    },
                    "example": {"detail": "未找到ID为ngo_999的NGO"}
                }
            }
        }
    }
)
async def get_ngo_by_id(ngo_id: str = Path(..., description="NGO的唯一ID")):
    # Firestore查询逻辑
    doc_ref = db.collection("ngos").document(ngo_id)
    doc = doc_ref.get()
    
    if not doc.exists:
        return responses.JSONResponse(status_code=404, content={"detail": "NGO不存在"})
    
    # 将Firestore文档转为字典并返回
    return responses.JSONResponse(content=doc.to_dict())

关键说明

  1. responses参数的作用:FastAPI默认会根据返回值推断响应结构,但直接返回JSONResponse时无法自动生成准确的Schema,所以需要通过responses手动定义符合OpenAPI规范的响应结构,包括状态码、描述、Schema和示例。
  2. Schema字段定义:通过schema里的properties指定每个字段的类型(比如string、date-time格式),required数组标记必须返回的字段,保证Swagger文档能清晰展示响应的结构要求。
  3. 示例值配置:example字段直接填写你期望的响应示例,Swagger页面会直接展示这个示例,方便前端开发者参考。

这样配置后,打开Swagger文档(默认路径/docs),就能看到该接口的响应Schema和自定义示例值,不再是默认的"string"了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:37:42