如何为路径参数启用 gt、lt 范围校验并返回 422 自定义错误?
解读
面试官想确认三件事:
- 你是否知道 FastAPI 把“路径参数”也当成 Pydantic Field,因此可以写 ge、le、gt、lt;
- 你是否能在 Path() 里写校验规则,而不是手动在业务代码里 if/raise;
- 当校验失败时,能否把框架默认的 422 响应体改成国内项目常用的统一格式(code、msg、data),而不是直接把英文堆栈抛给前端。
国内大厂/独角兽的接口规范通常要求:
- HTTP 状态码保持 422(语义正确,网关不报警);
- 响应体必须是 {“code”:xxx,“msg”:“xxx”,“data”:null};
- 日志里要保留原始异常,方便排障。
因此,回答要覆盖“校验声明 + 异常重写 + 日志保留”三件套,才能体现工程化思维。
知识点
- Path(..., gt=, lt=) 的用法与内部原理:FastAPI 会把 Path 转成 Pydantic FieldInfo,再由 pydantic 生成 JSON Schema,最后由 starlette 的 RequestValidationError 抛出。
- RequestValidationError 的响应体结构:{“detail”:[{“loc”:[“path”,“item_id”],“msg”:“ensure this value is greater than 0”,“type”:“value_error.number.not_gt”}]}。
- 自定义异常处理器:app.add_exception_handler(RequestValidationError, handler),handler 内部可区分 loc 类型,组装成业务方要求的格式。
- 日志规范:使用 structlog 或 loguru 把原始 detail 序列化后写到 extra,方便 ELK 索引;同时给前端返回脱敏信息,防止泄漏内部字段。
- 测试技巧:TestClient 触发 422 后,断言 response.json()["code"] 与 loc,体现 TDD 习惯。
答案
from fastapi import FastAPI, Path, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
import logging
app = FastAPI()
# 统一响应工具
def fail(code: int, msg: str):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"code": code, "msg": msg, "data": None}
)
# 全局异常处理
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
# 只处理路径参数校验失败
for err in exc.errors():
if err["loc"][0] == "path":
# 日志保留原始错误
logging.warning("path validation error: %s", err, extra={"raw": exc.errors()})
# 业务友好提示
return fail(40001, "路径参数超出允许范围")
# 其他字段校验仍走默认
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"code": 40000, "msg": "参数校验失败", "data": exc.errors()},
)
# 业务接口
@app.get("/items/{item_id}")
async def get_item(
item_id: int = Path(..., gt=0, lt=100, description="商品ID,范围 1-99")
):
return {"item_id": item_id}
运行验证:
GET /items/0 → 422 {"code":40001,"msg":"路径参数超出允许范围","data":null}
GET /items/50 → 200 {"item_id":50}
拓展思考
- 如果范围值是动态配置(例如从配置中心读取),可以把 gt/lt 换成 Depends + 自定义验证器,在启动时预热,避免每次请求都读配置。
- 当接口版本升级需要兼容旧范围时,可利用 Path 的 alias 与额外校验器,实现“灰度”提示:新范围报错时返回特殊 code,方便监控统计。
- 对于批量路径参数(如
/items/{start}-{end}),可自定义 Pydantic 类型,在 get_validators 里一次性校验 start<end 且区间长度<=100,减少重复代码。 - 在微服务网关层(Kong、APISIX)也可以做同样的范围校验,但业务语义校验仍应下沉到服务自身,保证“Fail Fast”同时不泄漏内部规则。