python type_error ai_generated true

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

ID: python/starlette-route-param-type-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-07-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

在 Starlette 路由中定义了路径参数类型为 int,但客户端传入了非数字字符串。

generic

中文

在 Starlette 路由中定义了路径参数类型为 int,但客户端传入了非数字字符串。

Workarounds

  1. 90% success
    from starlette.routing import Route
    async def get_item(request):
        id = request.path_params['id']
        try:
            id = int(id)
        except ValueError:
            return JSONResponse({'error': 'invalid'}, status_code=400)
  2. 95% success
    Route('/items/{id:int}', get_item)

Dead Ends

Common approaches that don't work:

  1. 60% fail

    如果参数是 URL 路径的一部分,无法在客户端转换。

  2. 50% fail

    改变了 API 设计,可能影响其他依赖该参数类型的代码。