1. 基础用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from fastapi import FastAPI, Path from typing import Annotated
app = FastAPI()
@app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], q: Annotated[str | None, Query(alias="item-query")] = None ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
|
- 使用
Path() 声明路径参数验证
- 路径参数默认必需,必须包含在 URL 路径中
- 支持同时声明路径参数和查询参数
2. 元数据声明
1 2 3 4 5
| item_id: Annotated[int, Path( title="商品ID", description="必须是正整数", example=5 )]
|
title 定义参数标题(显示在文档中)
description 添加参数描述说明
example 提供示例值
3. 数值验证
1 2 3 4 5
| @app.get("/items/{num}") async def validate_num( num: Annotated[int, Path(ge=1, le=100)] ): return {"num": num}
|
- 支持多种数值约束:
gt:大于(greater than)
ge:大于等于
lt:小于
le:小于等于
- 无效数值会触发 422 验证错误
4. 多版本兼容
Python 3.8+ 兼容写法:
1 2 3 4 5 6 7 8 9
| from typing import Union from fastapi import Path
@app.get("/items/{item_id}") async def read_items( item_id: int = Path(..., ge=1), q: Union[str, None] = Query(default=None) ): ...
|
- 旧版使用
Query()/Path() 直接添加验证
- 新版推荐优先使用
Annotated
5. 高级特性
1 2 3
| @app.get("/files/{file_path:path}") def filepath(file_path: str): return {"file_path": file_path}
|
- 路径参数包含路径时使用
:path 转换器
- 支持正则表达式验证(通过
regex 参数)
6. 最佳实践
- 路径参数默认必需,无需声明默认值
- 数值验证时明确边界条件(如
ge=1)
- 复杂验证建议使用枚举类或自定义类型
- 通过
alias 处理特殊字符参数名
- FastAPI ≥0.95.1 推荐使用
Annotated
提示:所有验证错误自动生成结构化响应,可通过 /docs 查看交互式文档中的验证规则说明。路径参数顺序会影响路由匹配,固定路径应声明在动态路径之前 。