FastAPI: 422 Unprocessable Entity
FastAPIでリクエストバリデーションが失敗した際のエラー原因と解決策
概要
FastAPIでリクエストボディやパラメータがPydanticモデルのバリデーションに失敗した際に発生するエラーです。
エラーメッセージ
```json { “detail”: [ { “loc”: [“body”, “email”], “msg”: “value is not a valid email address”, “type”: “value_error.email” } ] } ```
原因
- 型の不一致: 期待する型と異なるデータ
- 必須フィールドの欠落: required フィールドが未送信
- バリデーションルール違反: 文字数制限、パターン等
- Content-Type の誤り: JSON以外で送信
解決策
1. Pydanticモデルを確認
```python from pydantic import BaseModel, EmailStr, Field from typing import Optional
class UserCreate(BaseModel): email: EmailStr name: str = Field(…, min_length=1, max_length=100) age: Optional[int] = Field(None, ge=0, le=150)
class Config:
# 未知のフィールドを無視
extra = 'ignore'
```
2. リクエストを正しく送信
```bash
正しいContent-Type
curl -X POST http://localhost:8000/users
-H “Content-Type: application/json”
-d ‘{“email”: “user@example.com”, “name”: “John”}’
```
3. カスタムバリデーションを追加
```python from pydantic import BaseModel, validator
class UserCreate(BaseModel): password: str password_confirm: str
@validator('password_confirm')
def passwords_match(cls, v, values):
if 'password' in values and v != values['password']:
raise ValueError('passwords do not match')
return v
```
4. エラーレスポンスをカスタマイズ
```python from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): errors = [] for error in exc.errors(): errors.append({ ‘field’: ‘.’.join(str(x) for x in error[’loc’]), ‘message’: error[‘msg’] }) return JSONResponse( status_code=422, content={’errors’: errors} ) ```
よくある間違い
- form-data で JSON を送信
- オプショナルフィールドに None ではなく空文字を送信
- 日付形式の不一致
関連エラー
関連エラー
Python の他のエラー
この記事は役に立ちましたか?