python type_error ai_generated true

fastapi.exceptions.RequestValidationError: 422: Field required

ID: python/fastapi-requestvalidationerror-query-parameter-missing

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

A required query parameter or path parameter was not provided in the request.

generic

中文

请求中未提供必需的查询参数或路径参数。

Workarounds

  1. 95% success Use Optional type with default None.
    from typing import Optional
    from fastapi import FastAPI, Query
    app = FastAPI()
    @app.get('/items/')
    async def read_items(q: Optional[str] = Query(None)):
        return {'q': q}
  2. 90% success Set default value directly.
    @app.get('/items/')
    async def read_items(q: str = 'default'):
        return {'q': q}

Dead Ends

Common approaches that don't work:

  1. Adding a default value of None without Optional type. 60% fail

    Without Optional, FastAPI still treats it as required and will raise validation error if missing.

  2. Using Query(None) without Optional. 70% fail

    Query(None) sets default to None but type hint still requires the field, causing validation error.