python type_error ai_generated true

ValueError: Invalid type for path parameter 'id': expected int, got str

ID: python/starlette-route-param-type

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Starlette route path parameters must be type-converted; if the URL provides a string but the handler expects int, this error occurs if conversion fails.

generic

中文

Starlette 路由路径参数必须进行类型转换;如果 URL 提供字符串但处理程序期望 int,转换失败时会报错。

Workarounds

  1. 95% success Use int type hint in the route parameter
    async def handler(request):
        id = request.path_params['id']
        # id is already an int
  2. 90% success Add a converter in the route pattern
    routes = [Route('/items/{id:int}', handler)]

Dead Ends

Common approaches that don't work:

  1. Using a string parameter and converting manually 70% fail

    Starlette auto-converts based on type hints; manual conversion may cause mismatch.

  2. Not specifying a type hint 80% fail

    Without type hint, Starlette treats it as str.