python type_error ai_generated true

TypeError: Path parameter 'id' must be an integer

ID: python/starlette-route-parameter-type-conversion

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Starlette路由参数类型转换失败,预期整数但收到其他类型

generic

中文

Starlette路由参数类型转换失败,预期整数但收到其他类型

Workarounds

  1. 95% success 确保URL路径包含有效整数
    GET /items/123
  2. 90% success 在路由定义中使用字符串类型并手动验证
    from starlette.routing import Route
    async def endpoint(request):
        id = request.path_params['id']
        if not id.isdigit():
            return JSONResponse({'error': 'Invalid ID'}, status_code=400)

Dead Ends

Common approaches that don't work:

  1. 在路由处理函数中手动转换类型 50% fail

    Starlette在调用函数前已尝试转换,失败会抛出异常

  2. 使用字符串类型参数忽略转换 40% fail

    类型转换是路由定义的一部分,忽略可能导致逻辑错误