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

如何将msgspec.Struct生成的JSON Schema用于FastAPI接口响应文档?

解决方法

1. 将msgspec生成的JSON Schema直接注入FastAPI的OpenAPI文档

FastAPI允许通过路由的openapi_extra字段自定义响应的Schema,你可以把msgspec.json.schema()生成的Schema直接指定到响应结构中:

import msgspec
from fastapi import FastAPI

app = FastAPI()

# 定义msgspec Struct
class User(msgspec.Struct):
    id: int
    name: str
    email: str

# 生成JSON Schema
user_schema = msgspec.json.schema(User)

@app.get("/user", openapi_extra={
    "responses": {
        200: {
            "description": "A user object",
            "content": {
                "application/json": {
                    "schema": user_schema
                }
            }
        }
    }
})
def get_user():
    return User(id=1, name="John", email="john@example.com")

这样FastAPI生成的OpenAPI文档就会直接使用你传入的msgspec Schema作为该接口的响应体定义。

2. 从JSON Schema生成可用于文档的Pydantic模型

Pydantic v2支持直接从JSON Schema生成模型,你可以利用pydantic.TypeAdapter来实现:

import msgspec
from pydantic import TypeAdapter
from fastapi import FastAPI

app = FastAPI()

class User(msgspec.Struct):
    id: int
    name: str
    email: str

user_schema = msgspec.json.schema(User)
# 从JSON Schema生成Pydantic模型
UserPydantic = TypeAdapter.from_json_schema(user_schema).type_

@app.get("/user", response_model=UserPydantic)
def get_user():
    return User(id=1, name="John", email="john@example.com")

生成的UserPydantic可以直接作为FastAPI路由的response_model使用,FastAPI会自动基于这个模型生成对应的OpenAPI文档,同时不影响你实际返回msgspec Struct实例(FastAPI会自动处理序列化)。

如果用的是Pydantic v1,可以使用pydantic.create_model_from_json_schema方法来实现类似功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:33:13