python type_error ai_generated true

TypeError: 'str' object cannot be interpreted as an integer

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-10-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

A route parameter expected as an integer is passed as a string without conversion.

generic

中文

预期为整数的路由参数以字符串形式传递,未进行转换。

Workarounds

  1. 90% success Convert the parameter to int explicitly
    async def get_item(item_id: str):
        item_id = int(item_id)
  2. 95% success Use Starlette's path converter for int
    @app.route('/items/{item_id:int}')
    async def get_item(item_id: int):
        ...

Dead Ends

Common approaches that don't work:

  1. Using str() on the parameter 80% fail

    Doesn't convert to int; keeps it as string.

  2. Ignoring the type and using the string directly 70% fail

    May cause errors in logic expecting an integer.