python
type_error
ai_generated
true
ValueError: Invalid type for path parameter 'id': expected int, got str
ID: python/starlette-route-param-type
80%Fix Rate
85%Confidence
0Evidence
2024-11-03First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success Use int type hint in the route parameter
async def handler(request): id = request.path_params['id'] # id is already an int -
90% success Add a converter in the route pattern
routes = [Route('/items/{id:int}', handler)]
Dead Ends
Common approaches that don't work:
-
Using a string parameter and converting manually
70% fail
Starlette auto-converts based on type hints; manual conversion may cause mismatch.
-
Not specifying a type hint
80% fail
Without type hint, Starlette treats it as str.