できない.dev

FastAPI「ResponseValidationError」の原因と直し方

ResponseValidationError は、返す値を response_model に合わせるか、モデルの項目を任意にすれば直る。
クライアントには 500 しか返らず、合わない項目はサーバーのログの loc と msg に出る。

公開: 更新:

症状できない
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/missing
Internal Server Error
500

2026-11-16 に python:3.12(FastAPI 0.163.1) で実際に打って取った出力。検証環境の詳細

要約

FastAPI のルートが返した値を response_model で検証したところ、合わなかったときに出るのが ResponseValidationError である。
クライアントには Internal Server Error の 500 だけが返り、理由はサーバーのログにしか出ない。
FastAPI 0.162.0・Pydantic 2.14.2(Python 3.12)では、ログに次のように出た。

INFO:     127.0.0.1:42890 - "GET /missing HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  ...
fastapi.exceptions.ResponseValidationError: 1 validation error:
  {'type': 'missing', 'loc': ('response', 'email'), 'msg': 'Field required', 'input': {'id': 1, 'name': 'a'}}

FastAPI は response_model か戻り値の型注釈に書いたモデルで、返す値を検証する。
公式のResponse Model(新しいタブで開く)によると、合わない値はアプリのコードの誤りとみなされ、間違ったデータを返す代わりにサーバーエラーになる。
ログの loc と msg を読み、返す値かモデルのどちらかを直せば 500 は消える。

loc の 1 つ目は常に response である。
項目が合わないときは 2 つ目にその項目名が入り、値そのものの形が合わないときは ('response',) だけになる。
上の例では、モデルの必須項目 email を返していない。

実行例

python:3.12 で必須項目 email の無い dict を返すと、クライアントには HTTP 500 が返り、ログには loc が ('response', 'email') の ResponseValidationError が出た。
email を任意にすると 200、見つからないときに HTTPException を投げると 404 になった。

$ curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/missing
Internal Server Error
500
$ grep -A1 "^fastapi.exceptions.ResponseValidationError" server.log
fastapi.exceptions.ResponseValidationError: 1 validation error:
  {'type': 'missing', 'loc': ('response', 'email'), 'msg': 'Field required', 'input': {'id': 1, 'name': 'a'}}
$ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/bad-type
500
$ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/none
500
$ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/list
500
$ grep "'loc'" server.log
  {'type': 'missing', 'loc': ('response', 'email'), 'msg': 'Field required', 'input': {'id': 1, 'name': 'a'}}
  {'type': 'int_parsing', 'loc': ('response', 'id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'abc'}
  {'type': 'model_attributes_type', 'loc': ('response',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': None}
  {'type': 'list_type', 'loc': ('response',), 'msg': 'Input should be a valid list', 'input': {'id': 1, 'name': 'a', 'email': 'a@example.com'}}
$ curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/optional
{"id":1,"name":"a","email":null}
200
$ curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/users/1
{"detail":"User not found"}
404

— 2026-11-16 時点の出力

検証環境Python 3.12.16 / Git 2.47.3 / FastAPI 0.163.1 / 2026-11-16 検証
検証日
実行環境
python:3.12 Debian GNU/Linux 13 (trixie)
バージョン
  • Python 3.12.16
  • Git 2.47.3
  • FastAPI 0.163.1

この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。

解決策

1. 足りない項目を返すか、任意にする

ログの loc に出た項目を、返す値に足す。
いつも返せるとは限らない項目なら、モデルの側で既定値を付けて任意にする。

class User(BaseModel):
    id: int
    name: str
    email: str | None = None

この形にすると、{"id": 1, "name": "a"} を返すルートは 200 になり、応答は {"id":1,"name":"a","email":null} だった。

2. 見つからないときは 404 を投げる

from fastapi import HTTPException
 
@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: int):
    user = find_user(user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

例外を投げたときは応答の検証は走らず、{"detail":"User not found"} の 404 が返った。
None を返すこと自体が仕様なら、response_model=User | None にすれば null の 200 になる。

3. 型と形をそろえる

list[User] と宣言したルートは、1 件でも [item] のようにリストで返す。
型が合わない項目は、データベースなどから読んだ値の型を確かめ、返す前に変換するかモデルの型を合わせる。

4. 検証そのものを外す

response_model=None を付けると、そのルートでは応答モデルが作られず、検証も行われない。
戻り値の型注釈が -> User のままでも、項目の欠けた dict がそのまま 200 で返った。
応答の形が保証されなくなるので、1〜3 で直せないルートに限って使う。

よくある原因

  1. モデルの必須項目を返していない。
    既定値の無い項目は必須になり、欠けると missing(Field required)になる。
    response_model を書かず、def annot() -> User: のように戻り値の型注釈だけを書いたルートでも同じ 500 になった。
  2. 型の合わない値を返している。
    id: int の項目に "abc" を返すと、loc が ('response', 'id') の int_parsing になる。
  3. None を返している。
    見つからなかったときに return None と書くと、loc が ('response',) だけの model_attributes_type になり、msg は Input should be a valid dictionary or object to extract fields from だった。
  4. 一覧のルートで 1 件分を返している。
    response_model=list[User] のルートで dict を 1 つ返すと、list_type(Input should be a valid list)になる。

返す値は dict でなくてもよい。
id・name・email の属性を持つだけの普通のクラスのインスタンスは、そのまま 200 で返った。
属性がそろっているかどうかで決まる。