python data_error ai_generated true

FastAPI请求验证错误:值不是有效的整数

fastapi.exceptions.RequestValidationError: value is not a valid integer

ID: python/fastapi-query-param-validation-error

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

版本兼容性

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

根因分析

期望为整数的查询参数被提供为非数字字符串或缺失。

English

A query parameter expected to be an integer is provided as a non-numeric string or missing.

generic

解决方案

  1. 95% 成功率
    Use type hints: def read_item(item_id: int = Query(...)):
  2. 90% 成功率
    Catch RequestValidationError and return a custom message.

无效尝试

常见但无效的做法:

  1. 70% 失败

    Using int() conversion in the function body can raise ValueError instead of a proper validation error.

  2. 60% 失败

    Setting a default value of 0 masks the error but allows invalid data.