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

- **ID:** `python/fastapi-query-param-type-error`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

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

@app.get('/items')
def read_items(item: Item = Query(...)):
    return item
   ```

## 无效尝试

- **Using a custom class without type conversion** — FastAPI cannot automatically convert custom types. (90% 失败率)
- **Setting default value as string but type hint as int** — Mismatch between default and type hint causes validation issues. (80% 失败率)
