【问题标题】:How to add documentation for required query parameters?如何为所需的查询参数添加文档?
【发布时间】:2020-11-23 17:08:20
【问题描述】:

我正在尝试创建一个依赖于 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 成为必需并保留文档功能?

【问题讨论】:

    标签: python fastapi


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

    • Query(...) 中的example=1 是什么?
    • 这是一个很好的问题。只需像默认值一样添加示例值,如果查询为空,则该查询将为 1,有点像当您打开 POST 端点的主体时,默认情况下将有相同的示例值,对于 str 将有"string",对于 int 会有 0 等。
    • 但这只是一个示例,当您向/endpoint 发送请求而没有任何查询参数时,您仍然会收到错误{"detail":[{"loc":["query","par1"],"msg":"field required","type":"value_error.missing"}
    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多