api request_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
90%Fix Rate
87%Confidence
1Evidence
2023-08-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
OpenAPI 3.0+ active
Django REST Framework 3.14+ active
FastAPI 0.100+ active

Root Cause

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

中文

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

Official Documentation

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

Workarounds

  1. 95% success Ensure the client sends the parameter as a raw integer in the URL (e.g., `?id=123` not `?id="123"`). In JavaScript, use `encodeURIComponent` but avoid quoting numbers. Example: `fetch('/api/resource?id=' + 123)`.
    Ensure the client sends the parameter as a raw integer in the URL (e.g., `?id=123` not `?id="123"`). In JavaScript, use `encodeURIComponent` but avoid quoting numbers. Example: `fetch('/api/resource?id=' + 123)`.
  2. 85% success Update the API schema to accept string parameters and perform server-side type coercion (e.g., using `int()` in Python with error handling). Example FastAPI: `@app.get("/items/{item_id}")` with `item_id: int`.
    Update the API schema to accept string parameters and perform server-side type coercion (e.g., using `int()` in Python with error handling). Example FastAPI: `@app.get("/items/{item_id}")` with `item_id: int`.
  3. 90% success Log the raw query string on the server to debug the exact value sent. Example: `print(request.query_params)` in Django, then compare with expected format.
    Log the raw query string on the server to debug the exact value sent. Example: `print(request.query_params)` in Django, then compare with expected format.

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 70% fail

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

  3. 80% fail

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