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.
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
- Read the
locin the ResponseValidationError to find the missing or wrong field. - Populate every required field on the returned object.
- Enable attribute reading if returning ORM instances.
from pydantic import BaseModel, ConfigDict
class ItemOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: strAssert the shape in a test
Add a test that checks the response body against the model so drift fails fast.
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=Truewhen returning ORM instances. - Test response shape so model drift is caught in CI.