python type_error ai_generated true

FastAPI 请求验证错误:查询参数 'page' 不是有效的整数

fastapi.exceptions.RequestValidationError: 1 validation error for Request query -> page value is not a valid integer (type=type_error.integer)

ID: python/fastapi-query-parameter-type-error

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

版本兼容性

版本状态引入弃用备注
3.9 active
3.10 active

根因分析

客户端提供的查询参数 'page' 无法转换为整数类型

English

客户端提供的查询参数 'page' 无法转换为整数类型

generic

解决方案

  1. 95% 成功率 提供有效的整数值
    GET /items?page=1
  2. 90% 成功率 使用 Query 设置默认值
    from fastapi import Query
    @app.get('/items')
    def get_items(page: int = Query(1, ge=1)):
        ...

无效尝试

常见但无效的做法:

  1. 将参数类型改为 str 并手动转换 60% 失败

    失去了自动验证功能,可能引入其他错误

  2. 在客户端忽略类型检查 80% 失败

    服务器端仍然会验证并返回错误