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

如何为FastAPI中anyOf类型的每个选项设置独立文档描述?

为FastAPI联合类型字段添加差异化文档描述

问题背景

在FastAPI中使用联合类型(如Dict | str、UUID | str)定义Pydantic模型字段时,自动生成的OpenAPI文档(Redoc/Swagger)默认会为所有联合类型成员共享同一标题和描述,导致文档显示重复信息,用户难以区分不同输入类型的具体要求。

现有功能正常但文档存在缺陷的代码

from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
from typing import Dict

class DictOrString(BaseModel):
    arg: Dict | str = Field(None, title="Dict or String?", description="my desc")

app = FastAPI()

@app.post("/mixed", description="Try mixing models anyOf")
async def mixed(inputs: DictOrString = Body()):
    return {"arg": inputs.arg, "type": f"{type(inputs.arg)=}"}

上述代码能正常解析字典和字符串输入,但文档中anyOf下的两种类型会重复显示相同的标题和描述,无法分别说明不同输入类型的要求。

解决方案:为每个联合类型成员单独设置文档元数据

可以通过两种方式实现差异化的文档描述:

方式一:通过Field的anyOf参数直接定义子schema元数据

from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
from typing import Dict, Annotated

class DictOrString(BaseModel):
    arg: Annotated[
        Dict | str,
        Field(
            None,
            anyOf=[
                {"title": "字典输入", "description": "传入JSON格式的键值对对象,例如 `{\"key\": \"value\"}`"},
                {"title": "字符串输入", "description": "传入普通文本字符串,例如 `\"hello world\"`"}
            ]
        )
    ] = None

app = FastAPI()

@app.post("/mixed", description="支持字典或字符串两种输入类型")
async def mixed(inputs: DictOrString = Body()):
    return {"arg": inputs.arg, "type": f"{type(inputs.arg)=}"}

方式二:为每个联合类型成员单独使用Annotated+Field

from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
from typing import Dict, Union, Annotated

class DictOrString(BaseModel):
    arg: Union[
        Annotated[Dict, Field(title="字典输入", description="JSON格式的键值对对象")],
        Annotated[str, Field(title="字符串输入", description="普通文本字符串")]
    ] = None

app = FastAPI()

@app.post("/mixed", description="支持字典或字符串两种输入类型")
async def mixed(inputs: DictOrString = Body()):
    return {"arg": inputs.arg, "type": f"{type(inputs.arg)=}"}

效果说明

使用以上两种方式后,FastAPI的Redoc或Swagger文档会为anyOf下的每个类型单独显示对应的标题和描述,用户能清晰区分不同输入类型的要求,解决了原文档的混淆问题。这种方法同样适用于其他任意联合类型组合(如UUID | str、int | float等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:30:19