0%

FastAPI自学教程(8)- 路径参数数值验证

1. 基础验证方法

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

app = FastAPI()

@app.get("/items/{item_id}")
async def read_items(
item_id: int = Path(..., title="商品ID", ge=1),
q: str | None = None
):
return {"item_id": item_id}
  • 使用 Path() 声明路径参数验证规则
  • ge=1 表示参数必须 ≥1
  • 省略号 ... 表示该参数为必需项

2. 数值范围验证

1
2
3
4
5
@app.get("/users/{user_id}")
async def read_user(
user_id: int = Path(..., gt=0, le=1000)
):
return {"user_id": user_id}
  • 支持四种数值约束:
    • gt:严格大于(>)
    • ge:大于等于(≥)
    • lt:严格小于(<)
    • le:小于等于(≤)
  • 示例约束 gt=0, le=1000 表示 0 < user_id ≤ 1000

3. 元数据增强

1
2
3
4
5
6
7
from typing import Annotated

@app.get("/products/{prod_id}")
async def get_product(
prod_id: Annotated[int, Path(title="产品ID", description="必须大于1000", example=1001, gt=1000)]
):
return {"prod_id": prod_id}
  • Annotated 语法支持同时声明:
    • 类型提示(int)
    • 验证规则(gt=1000)
    • 文档元数据(title/description/example)

4. 多参数验证

1
2
3
4
5
6
7
8
9
@app.get("/stores/{store_id}/items/{item_id}")
async def read_store_item(
store_id: int = Path(..., gt=100),
item_id: int = Path(..., lt=50)
):
return {
"store_id": store_id,
"item_id": item_id
}
  • 支持多个路径参数独立验证
  • 参数验证顺序不影响功能
  • 每个参数都有自己的验证规则

5. 高级用法

1
2
3
4
5
6
@app.get("/files/{file_path:path}")
async def read_file(
file_path: str = Path(..., min_length=5),
version: int = Path(..., ge=2020)
):
return {"path": file_path, "version": version}
  • :path 转换器支持包含斜杠的路径参数
  • 混合使用路径格式和数值验证
  • 支持字符串长度验证(min_length/max_length)

文档支持:所有验证规则会自动展示在 /docs 页面,包含:

  • 参数类型要求
  • 数值边界说明
  • 示例值展示
  • 错误响应示例(HTTP 422)