5

我正在尝试创建一个依赖于 HTTP GET 参数的 fastapi API 端点,将它们记录在案并使用 fastapi 的验证功能。考虑以下最小示例:

import fastapi

app = fastapi.FastAPI(
)

@app.get("/endpoint")
def example_endpoint(
    par1: int = fastapi.Query(
        None,
        description="example documentation1",
    ),

    par2: int = fastapi.Query(
        None,
        description="example documentation2",
    ),
):
    return {"test": par1 + par2}

这具有文档支持并适用于 HTTP GET 参数,但不验证它们 - http://localhost:8000/endpoint?par1=2&par2=3 工作正常,但 http://localhost:8000/endpoint 崩溃内部服务器错误,而不是通知用户需要一个参数。有没有办法使 par1 和 par2 成为必需并保留文档功能?

4

1 回答 1

8

您可以使用Ellipsis,如果您以前没有见过...:它是一个特殊的单个值,需要查询

from fastapi import Query

Query(...,description="example documentation1")

所以在你的情况下,下面的答案可以完成这项工作

@app.get("/endpoint")
def example_endpoint(
    par1: int = fastapi.Query(..., description="example documentation1",),
    par2: int = fastapi.Query(..., description="example documentation2",),
):

    if par1 and par2:
        return {"test": par1 + par2}

    raise ValueError("Missing query parameters")

你也可以使用example=1

Query(..., description="example documentation2", example=1)
于 2020-08-03T16:33:39.433 回答