python data_error ai_generated true

fastapi.exceptions.RequestValidationError: 1 validation error for Request query -> page Input should be a valid integer, unable to parse string as an integer

ID: python/fastapi-request-validation-query

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-07-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —

Root Cause

A query parameter declared as int received a non-numeric string (often empty or 'abc') from the client.

generic

中文

声明为 int 的查询参数收到了客户端传来的非数字字符串(通常是空值或 'abc')。

Workarounds

  1. 95% success
    from fastapi import Query
    @app.get('/items')
    async def items(page: int = Query(1, ge=1)): ...
  2. 85% success
    @app.exception_handler(RequestValidationError)
    async def handler(req, exc):
        return JSONResponse(status_code=422, content={'errors': exc.errors()})

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Clients keep sending bad data and pagination logic receives None.

  2. 70% fail

    Moves the failure to an uncaught ValueError deeper in the stack.