python type_error ai_generated true

FastAPI 错误:查询参数 'age' 的类型无效:<class 'str'> 不是有效的查询参数类型。

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

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-07-14首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

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

English

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

解决方案

  1. 95% 成功率 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% 成功率 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

无效尝试

常见但无效的做法:

  1. Using a custom class without type conversion 90% 失败

    FastAPI cannot automatically convert custom types.

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

    Mismatch between default and type hint causes validation issues.