声明不属于路径参数的其他函数参数时,它们将被自动解释为”查询字符串”参数

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
  4. @app.get("/items/")
  5. async def read_item(skip: int = 0, limit: int = 10):
  6. return fake_items_db[skip : skip + limit]

查询字符串是键值对的集合,这些键值对位于 URL 的 之后,并以 & 符号分隔。
例如,在以下 url 中:

  1. http://127.0.0.1:8000/items/?skip=0&limit=10

…查询参数为:

  • skip:对应的值为 0
  • limit:对应的值为 10

由于它们是 URL 的一部分,因此它们的”原始值”是字符串。
但是,当你为它们声明了 Python 类型(在上面的示例中为 int)时,它们将转换为该类型并针对该类型进行校验。
应用于路径参数的所有相同过程也适用于查询参数:

  • (很明显的)编辑器支持
  • 数据”解析”
  • 数据校验
  • 自动生成文档

    默认值

    由于查询参数不是路径的固定部分,因此它们可以是可选的,并且可以有默认值。
    在上面的示例中,它们具有 skip=0limit=10 的默认值。
    因此,访问 URL:

    1. http://127.0.0.1:8000/items/

    将与访问以下地址相同:

    1. http://127.0.0.1:8000/items/?skip=0&limit=10

    但是,如果你访问的是:

    1. http://127.0.0.1:8000/items/?skip=20

    函数中的参数值将会是:

  • skip=20:在 URL 中设定的值

  • limit=10:使用默认值

    可选参数

    通过同样的方式,你可以将它们的默认值设置为 None 来声明可选查询参数: ```python from typing import Optional from fastapi import FastAPI

app = FastAPI()

@app.get(“/items/{item_id}”) async def read_item(item_id: str, q: Optional[str] = None): if q: return {“item_id”: item_id, “q”: q} return {“item_id”: item_id}

  1. 在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`
  2. :::info
  3. 还要注意的是,**FastAPI** 足够聪明,能够分辨出参数 `item_id` 是路径参数而 `q` 不是,因此 `q` 是一个查询参数。
  4. :::
  5. <a name="_4"></a>
  6. ## 查询参数类型转换
  7. 你还可以声明 `bool` 类型,它们将被自动转换:
  8. ```python
  9. from typing import Optional
  10. from fastapi import FastAPI
  11. app = FastAPI()
  12. @app.get("/items/{item_id}")
  13. async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
  14. item = {"item_id": item_id}
  15. if q:
  16. item.update({"q": q})
  17. if not short:
  18. item.update(
  19. {"description": "This is an amazing item that has a long description"}
  20. )
  21. return item

这个例子中,如果你访问:

  1. http://127.0.0.1:8000/items/foo?short=1

  1. http://127.0.0.1:8000/items/foo?short=True

  1. http://127.0.0.1:8000/items/foo?short=true

  1. http://127.0.0.1:8000/items/foo?short=on

  1. http://127.0.0.1:8000/items/foo?short=yes

或任何其他的变体形式(大写,首字母大写等等),你的函数接收的 short 参数都会是布尔值 True。对于值为 False 的情况也是一样的。

多个路径和查询参数

你可以同时声明多个路径参数和查询参数,FastAPI 能够识别它们。
而且你不需要以任何特定的顺序来声明。
它们将通过名称被检测到:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. app = FastAPI()
  4. @app.get("/users/{user_id}/items/{item_id}")
  5. async def read_user_item(
  6. user_id: int, item_id: str, q: Optional[str] = None, short: bool = False
  7. ):
  8. item = {"item_id": item_id, "owner_id": user_id}
  9. if q:
  10. item.update({"q": q})
  11. if not short:
  12. item.update(
  13. {"description": "This is an amazing item that has a long description"}
  14. )
  15. return item

必需查询参数

当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。
如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 None
但当你想让一个查询参数成为必需的,不声明任何默认值就可以:

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/items/{item_id}")
  4. async def read_user_item(item_id: str, needy: str):
  5. item = {"item_id": item_id, "needy": needy}
  6. return item

这里的查询参数 needy 是类型为 str 的必需查询参数。
如果你在浏览器中打开一个像下面的 URL:

  1. http://127.0.0.1:8000/items/foo-item

…因为没有添加必需的参数 needy,你将看到类似以下的错误:

  1. {
  2. "detail": [
  3. {
  4. "loc": [
  5. "query",
  6. "needy"
  7. ],
  8. "msg": "field required",
  9. "type": "value_error.missing"
  10. }
  11. ]
  12. }

由于 needy 是必需参数,因此你需要在 URL 中设置它的值:

  1. http://127.0.0.1:8000/items/foo-item?needy=sooooneedy

…这样就正常了:

  1. {
  2. "item_id": "foo-item",
  3. "needy": "sooooneedy"
  4. }

当然,你也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. app = FastAPI()
  4. @app.get("/items/{item_id}")
  5. async def read_user_item(
  6. item_id: str, needy: str, skip: int = 0, limit: Optional[int] = None
  7. ):
  8. item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
  9. return item

在这个例子中,有3个查询参数:

  • needy,一个必需的 str 类型参数。
  • skip,一个默认值为 0int 类型参数。
  • limit,一个可选的 int 类型参数。


:::info 你还可以像在 路径参数 中那样使用 Enum。 :::

Optional 类型声明


:::warning 这可能是一个比较高级的使用场景。
您也可以跳过它。 :::

如果你正在使用 mypy,它可能会对如下的类型声明进行警告:

  1. limit: int = None

提示类似以下错误:

  1. Incompatible types in assignment (expression has type "None", variable has type "int")

在这种情况下,你可以使用 Optional 来告诉 mypy 该值可以为 None,例如:

  1. from typing import Optional
  2. limit: Optional[int] = None