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

如何在FastAPI的OpenAPI规范(Swagger UI)中配置参数可选值

FastAPI路径参数固定可选值+文档自动展示实现方案

推荐实现:使用字符串枚举类

FastAPI原生支持Python枚举类型作为参数类型注解,既能自动完成参数校验,还会自动将可选值同步到OpenAPI自动文档中,无需手动编写校验逻辑。
完整实现代码如下:

from fastapi import FastAPI
from enum import Enum

# 自定义枚举类定义所有允许的参数值
class AllowedParameter(str, Enum):
    a = "a"
    b = "b"
    c = "c"

app = FastAPI()

@app.get("/endpoint/{parameter}")
def endpoint(parameter: AllowedParameter):
    # 通过.value获取枚举对应的字符串值返回
    return {"parameter": parameter.value}

该方案的优势:

  • 自动完成参数校验:如果传入的值不在a/b/c范围内,FastAPI会直接返回标准的422校验错误响应,无需手动判断抛出HTTP异常
  • 自动文档同步:OpenAPI交互文档会自动识别枚举的可选值,在参数说明中直接展示可选范围,同时提供下拉选择框供调试使用,API用户无需猜测可选参数
  • 可维护性更高:后续需要新增允许的参数值时,只需要在AllowedParameter枚举类中新增成员即可,无需修改其他校验逻辑

替代方案(不推荐)

如果你暂时不想使用枚举,也可以通过Path校验器加正则限制参数范围:

from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/endpoint/{parameter}")
def endpoint(parameter: str = Path(pattern="^[abc]$")):
    return {"parameter": parameter}

注意:该方案仅会做参数校验,不会在OpenAPI文档中展示可选参数范围,因此不推荐使用


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:45:01