python data_error ai_generated true

ValueError: Invalid value for path parameter 'id': expected int, got 'abc'

ID: python/starlette-route-parameter-type

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2026-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

路径参数类型转换失败,例如期望整数但提供了字符串。

generic

中文

路径参数类型转换失败,例如期望整数但提供了字符串。

Workarounds

  1. 95% success
    使用类型转换装饰器:
    @app.route("/items/{id}")
    async def get_item(request, id: int):
        return {"id": id}
  2. 90% success
    手动转换并处理错误:
    try:
        id = int(request.path_params['id'])
    except ValueError:
        return JSONResponse(status_code=400, content={"error": "Invalid id"})

Dead Ends

Common approaches that don't work:

  1. 80% fail

    尝试使用int()强制转换但未捕获异常。

  2. 70% fail

    忽略错误,导致路由匹配失败。