0%

FastAPI自学教程(6)- 查询参数和字符串校验

1. 基础用法

1
2
3
4
5
6
7
8
9
10
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: str | None = None):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
  • 非路径参数自动解析为查询参数(如 q
  • 类型注解 str | None 表示可选参数
  • 默认值 = None 使参数非必需

2. 使用 Annotated 验证

1
2
3
4
5
6
from typing import Annotated
from fastapi import Query

@app.get("/items/")
async def read_items(q: Annotated[str | None, Query(max_length=50)] = None):
# 实现逻辑
  • 通过 Annotated 包装类型和验证元数据
  • Query(max_length=50) 添加长度限制验证
  • 支持同时声明类型和验证规则

3. 多版本兼容写法

Python 3.8+ 兼容版本:

1
2
3
4
5
6
7
8
from typing import Union
from fastapi import Query

@app.get("/items/")
async def read_items(
q: Union[str, None] = Query(default=None, max_length=50)
):
# 实现逻辑
  • 使用 Union 替代 | 操作符
  • 旧版 FastAPI (<0.95.0) 需通过 Query() 直接添加验证
  • 推荐优先使用 Annotated 版本

4. 验证参数类型

1
2
3
4
5
@app.get("/items/")
async def read_items(
q: Annotated[str | None, Query(min_length=3, max_length=50, pattern="^[a-z]+$")] = None
):
# 实现逻辑
  • 支持多种验证约束:
    • min_length/max_length:字符串长度限制
    • pattern:正则表达式验证
    • gt/ge/lt/le:数值范围验证

5. 自动文档支持

  • 交互式文档 /docs 自动显示:
    • 参数默认值
    • 验证规则说明
    • 枚举值示例(如正则模式)
    • 错误响应示例
  • 无效输入自动生成描述性错误(HTTP 422)

6. 最佳实践

  1. 优先使用 Annotated 声明方式(FastAPI ≥0.95.1)
  2. 复杂验证使用正则表达式时保持模式简单
  3. 通过 Query() 参数添加参数描述文档:
    1
    Query(default=None, description="搜索关键词,最多50个字符")
  4. 不同版本兼容处理时保持验证逻辑一致