如何使用FastAPI允许OpenAPI规范(Swagger UI)中的特定参数值?



我正在阅读路径参数验证教程。

我想允许字符串"a"b"one_answers";c"作为可能的参数值。我希望这些值显示在OpenAPI文档中(即FastAPI的自动文档),以便API用户不必猜测它们。如何使这些值显示在文档中?

这是我的实现:

from fastapi import FastAPI, HTTPException
app = FastAPI()
parameters = ["a", "b", "c"]
@app.get("/endpoint/{parameter}")
def endpoint(parameter: str):
if parameter not in parameters:
raise HTTPException(status_code=400, detail="parameter must be a, b, or c")
return {"parameter": parameter}

使用Enum进行参数验证,允许的值将出现在文档站点中。

from enum import Enum
from fastapi import FastAPI, HTTPException
app = FastAPI()
class AllowedParameterValues(str, Enum):
a = "a"
b = "b"
c = "c"

@app.get("/endpoint/{parameter}")
def endpoint(parameter: AllowedParameterValues):
return {"parameter": parameter}

选项1

您可以使用enums,通过创建Enum子类,如FastAPI文档中所述:

from enum import Enum
class MyParam(str, Enum):
a= "a"
b= "b"
c= "c"
@app.get("/{my_param}")
def index(my_param: MyParam):
return {"my_param": my_param}

选项2

或者,您可以使用Literal类型,它允许您指定参数可能只接受特定的Literal值:

from typing import Literal
@app.get("/{my_param}")
def index(my_param: Literal["a", "b", "c"]):
return {"my_param": my_param}

最新更新