FastAPI 中的可选查询参数

Optional query parameters in FastAPI

我不明白 optional query parameters in FastAPI. How is it different from default query parameters 默认值为 None?

在下面的示例中,arg1 和 arg2 之间有什么区别,其中 arg2 是如上所述的可选查询参数link?

@app.get("/info/")
async def info(arg1: int = None, arg2: int | None = None):
    return {"arg1": arg1, "arg2": arg2}

这取决于你的看法,但我的理念是:

可选参数是一个更大的集合,其中包括查询参数。

也就是说,查询参数接受作为值的输入,而可选参数是可以没有值的查询参数(即 None)。

这个is covered in the reference manual,尽管只是一个小笔记:

async def read_items(q: Optional[str] = None):

FastAPI will know that the value of q is not required because of the default value = None.

The Optional in Optional[str] is not used by FastAPI, but will allow your editor to give you better support and detect errors.

Optional[str] 与其他读者的 str | None pre 3.10 相同)

由于您的编辑器可能不知道 FastAPI 填充和使用参数的上下文,因此当参数时,它可能难以理解函数的实际签名未标记为 Optional。你可能关心也可能不关心这个区别。