api request_error ai_generated true

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

400 Bad Request: invalid query parameter type — expected integer but got string

ID: api/http-400-invalid-query-parameter-type

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2023-08-22首次发现

版本兼容性

版本状态引入弃用备注
OpenAPI 3.0+ active
Django REST Framework 3.14+ active
FastAPI 0.100+ active

根因分析

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

English

The client provided a query parameter with an incorrect data type (e.g., a string where an integer is required), often due to missing type coercion or incorrect serialization.

generic

官方文档

https://swagger.io/docs/specification/describing-parameters/

解决方案

  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)`,然后与预期格式比较。

无效尝试

常见但无效的做法:

  1. 90% 失败

    URL query parameters are strings by default; the server expects an unquoted integer, so quoting only adds extra characters and still fails.

  2. 70% 失败

    This alters the API contract and may break other clients or validation logic; it's a workaround that hides the real issue.

  3. 80% 失败

    The parameter is present but with wrong type; adding a default doesn't fix the type mismatch.