python type_error ai_generated true

fastapi.exceptions.FastAPIError: Invalid type for query parameter 'age': <class 'str'> is not a valid type for a query parameter.

ID: python/fastapi-query-param-type-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

FastAPI query parameters must have a type that can be parsed from strings; using unsupported types like str for a parameter that expects int causes this error.

generic

中文

FastAPI 查询参数必须具有可从字符串解析的类型;使用不支持的类型(如应为 int 却用了 str)会导致此错误。

Workarounds

  1. 95% success Use proper type hints like int, float, or str
    from fastapi import FastAPI, Query
    app = FastAPI()
    @app.get('/items')
    def read_items(age: int = Query(...)):
        return {'age': age}
  2. 90% success Use Pydantic models for complex types
    from pydantic import BaseModel
    class Item(BaseModel):
        age: int
    
    @app.get('/items')
    def read_items(item: Item = Query(...)):
        return item

Dead Ends

Common approaches that don't work:

  1. Using a custom class without type conversion 90% fail

    FastAPI cannot automatically convert custom types.

  2. Setting default value as string but type hint as int 80% fail

    Mismatch between default and type hint causes validation issues.