Skip to content
Latchkey

FastAPI "ResponseValidationError" from response_model in CI

FastAPI validates outgoing data against the response_model you declared. When a handler returns an object missing a required field or with the wrong type, FastAPI raises ResponseValidationError and the endpoint returns a 500 in tests.

What this error means

A test hitting an endpoint fails with a 500 and the server log shows "fastapi.exceptions.ResponseValidationError" listing which response fields did not validate.

python
fastapi.exceptions.ResponseValidationError: 1 validation errors:
  {'type': 'missing', 'loc': ('response', 'id'), 'msg': 'Field required',
   'input': {'name': 'widget'}}

Common causes

The returned object is missing a response field

The ORM row or dict the handler returns lacks a field the response_model marks required, so response validation fails.

A type mismatch or unset from_attributes

The handler returns an ORM object but the response model was not configured to read attributes, or a field type does not match.

How to fix it

Return data that matches the response_model

  1. Read the loc in the ResponseValidationError to find the missing or wrong field.
  2. Populate every required field on the returned object.
  3. Enable attribute reading if returning ORM instances.
app/schemas.py
from pydantic import BaseModel, ConfigDict

class ItemOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: int
    name: str

Assert the shape in a test

Add a test that checks the response body against the model so drift fails fast.

tests/test_api.py
r = client.get("/items/1")
assert r.status_code == 200
assert set(r.json()) >= {"id", "name"}

How to prevent it

  • Keep handlers returning objects that satisfy the response_model.
  • Set from_attributes=True when returning ORM instances.
  • Test response shape so model drift is caught in CI.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →