# 400 错误请求：查询参数类型无效 — 期望整数但得到字符串

- **ID:** `api/http-400-invalid-query-parameter-type`
- **领域:** api
- **类别:** request_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

客户端提供了数据类型不正确的查询参数（例如，需要整数却提供了字符串），通常是由于缺少类型强制转换或序列化错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OpenAPI 3.0+ | active | — | — |
| Django REST Framework 3.14+ | active | — | — |
| FastAPI 0.100+ | active | — | — |

## 解决方案

1. ```
   确保客户端在 URL 中以原始整数形式发送参数（例如 `?id=123` 而不是 `?id="123"`）。在 JavaScript 中，使用 `encodeURIComponent` 但避免对数字加引号。示例：`fetch('/api/resource?id=' + 123)`。
   ```
2. ```
   更新 API 架构以接受字符串参数并在服务器端执行类型强制转换（例如，在 Python 中使用带有错误处理的 `int()`）。FastAPI 示例：`@app.get("/items/{item_id}")` 使用 `item_id: int`。
   ```
3. ```
   在服务器端记录原始查询字符串以调试确切发送的值。示例：在 Django 中 `print(request.query_params)`，然后与预期格式比较。
   ```

## 无效尝试

- **** — URL query parameters are strings by default; the server expects an unquoted integer, so quoting only adds extra characters and still fails. (90% 失败率)
- **** — This alters the API contract and may break other clients or validation logic; it's a workaround that hides the real issue. (70% 失败率)
- **** — The parameter is present but with wrong type; adding a default doesn't fix the type mismatch. (80% 失败率)
