python
type_error
ai_generated
true
fastapi.exceptions.RequestValidationError: 422: Field required
ID: python/fastapi-requestvalidationerror-query-parameter-missing
80%Fix Rate
88%Confidence
0Evidence
2024-04-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
A required query parameter or path parameter was not provided in the request.
generic中文
请求中未提供必需的查询参数或路径参数。
Workarounds
-
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} -
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:
-
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.
-
Using Query(None) without Optional.
70% fail
Query(None) sets default to None but type hint still requires the field, causing validation error.