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

FastAPI中Swagger UI无法显示Model定义的Schema求助

FastAPI Swagger UI不显示Schema示例的解决方法

问题原因分析

你的代码采用了Pydantic v1的Config.schema_extra写法,若当前环境安装的是Pydantic v2,该写法会直接失效;另外部分接口返回类型定义为dict,导致Swagger无法识别对应模型结构,自然无法展示示例。

解决方案

方案1:适配Pydantic v2写法(推荐)

Pydantic v2已废弃Config子类配置方式,改用model_config字典配置,修改model.py代码如下:

from pydantic import BaseModel, ConfigDict

class Todo(BaseModel):
    id: int
    item: str

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "id": 1,
                "item": "Example Schema!"
            }
        }
    )

class TodoItem(BaseModel):
    item: str

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "item": "Read the next chapter of the book"
            }
        }
    )

方案2:保留Pydantic v1写法(需降级依赖)

若要继续使用原有Config子类写法,需确保安装Pydantic v1版本,执行以下命令:

pip install "pydantic<2.0"

额外优化:让响应体也显示模型示例

你的GET接口返回类型定义为dict,Swagger无法识别对应模型结构。修改接口返回类型为对应模型/模型列表,示例如下:

# 修改todo.py中的retrieve_todos接口
from typing import List

@todo_router.get("/todo")
async def retrieve_todos() -> dict[str, List[Todo]]:
    return {
        "todos": todo_list
    }

# 修改get_single_todo接口
@todo_router.get("/todo/{todo_id}")
async def get_single_todo(todo_id: int) -> dict[str, Todo]:
    for todo in todo_list:
        if todo.id == todo_id:
            return {
                "todo": todo
            }
    return {
        "message": "Todo with supplied ID doesn't exist."
    }

验证方法

重启FastAPI服务,访问http://localhost:8000/docs,查看POST /todo的请求体部分即可看到定义的示例;修改后的GET接口也会在响应体中展示模型结构和示例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:07:48