如何为必需的查询参数添加文档说明?

6
我想创建一个 FastAPI API 端点,它依赖于 HTTP GET 参数,有文档说明,并使用 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为必需,并保留文档功能?

1个回答

11

如果你之前没有看到过...,你可以使用省略号。它是一个特殊的单值,使查询必填

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)

1
Query(...) 中的 example=1 是什么意思? - JPG
这是一个很好的问题。简单来说,它添加了示例值,例如默认情况下,如果查询为空,则查询将为1,就像当您打开POST端点的Body时,默认情况下会有相同的示例值,对于str,将为"string",对于int,将为0等。 - Yagiz Degirmenci
但这只是一个例子,当您发送一个没有任何查询参数的请求到/endpoint时,您仍将收到一个错误{"detail":[{"loc":["query","par1"],"msg":"field required","type":"value_error.missing"} - Yagiz Degirmenci

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接