python
type_error
ai_generated
true
fastapi.exceptions.RequestValidationError: 422: 字段必填
fastapi.exceptions.RequestValidationError: 422: Field required
ID: python/fastapi-requestvalidationerror-query-parameter-missing
80%修复率
88%置信度
0证据数
2024-04-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
请求中未提供必需的查询参数或路径参数。
English
A required query parameter or path parameter was not provided in the request.
解决方案
-
95% 成功率 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% 成功率 Set default value directly.
@app.get('/items/') async def read_items(q: str = 'default'): return {'q': q}
无效尝试
常见但无效的做法:
-
Adding a default value of None without Optional type.
60% 失败
Without Optional, FastAPI still treats it as required and will raise validation error if missing.
-
Using Query(None) without Optional.
70% 失败
Query(None) sets default to None but type hint still requires the field, causing validation error.