0%

FastAPI自学教程(4)- 查询参数

1. 基础用法

1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
  • 非路径参数的函数参数自动解释为查询参数(如 skiplimit
  • 查询参数以 ?key=value&key2=value2 形式出现在 URL 中

2. 默认值

1
2
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
  • 访问 /items/ 等价于 /items/?skip=0&limit=10
  • 部分覆盖默认值时(如 ?skip=20),未指定的参数保持默认值

3. 可选参数

1
2
3
4
from typing import Optional

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
  • 通过 Optional[...] = Nonestr | None = None 声明可选参数
  • FastAPI 自动识别参数是否必需

4. 类型转换

1
2
@app.get("/items/{item_id}")
async def read_item(short: bool = False):
  • bool 类型支持多种字符串转换:1/True/true/yes/on 均转为 True
  • 无效类型会触发自动错误响应

5. 多参数处理

1
2
3
4
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: str | None = None, short: bool = False
):
  • 支持同时声明路径参数(user_id)和查询参数(q
  • 参数声明顺序不影响匹配

6. 必需参数

1
2
@app.get("/items/{item_id}")
async def read_user(item_id: str, name: str):
  • 没有默认值的参数自动成为必需查询参数
  • 缺少必需参数会返回 422 验证错误

7. 自动文档支持

  • 交互式文档 /docs 自动显示:
    • 参数类型要求
    • 默认值说明
    • 枚举值示例(如布尔参数显示可用值)