python data_error ai_generated true

fastapi.exceptions.RequestValidationError: path -> id:值不是有效的 uuid (type=type_error.uuid)

fastapi.exceptions.RequestValidationError: path -> id value is not a valid uuid (type=type_error.uuid)

ID: python/fastapi-path-param-422-uuid

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-07-08首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

路径参数声明为 UUID,但 URL 片段不是有效的 UUID 字符串。

English

The path parameter is declared as UUID but the URL segment is not a valid UUID string.

generic

解决方案

  1. 90% 成功率
    @app.get('/items/{item_id}')
    def get(item_id: str):
        try: uid = UUID(item_id)
        except ValueError: raise HTTPException(400)
  2. 88% 成功率
    from fastapi import Path
    def get(item_id: UUID = Path(...)): ...

无效尝试

常见但无效的做法:

  1. 75% 失败

    Still fails if the regex matches but the value is not a UUID.

  2. 90% 失败

    Validation runs before the handler; except never triggers.