{"record":{"id":"2dd261a1d0e75523","repo":"tiangolo/fastapi","slug":"n-validation-error-s-errors","errorCode":null,"errorMessage":"{n} validation error(s):\n{errors}","messagePattern":"(.+?) validation error\\(s\\):\n(.+?)","errorType":"validation","errorClass":"ResponseValidationError","httpStatus":null,"severity":"error","filePath":"fastapi/routing.py","lineNumber":324,"sourceCode":"    exclude: IncEx | None = None,\n    by_alias: bool = True,\n    exclude_unset: bool = False,\n    exclude_defaults: bool = False,\n    exclude_none: bool = False,\n    is_coroutine: bool = True,\n    endpoint_ctx: EndpointContext | None = None,\n    dump_json: bool = False,\n) -> Any:\n    if field:\n        if is_coroutine:\n            value, errors = field.validate(response_content, {}, loc=(\"response\",))\n        else:\n            value, errors = await run_in_threadpool(\n                field.validate, response_content, {}, loc=(\"response\",)\n            )\n        if errors:\n            ctx = endpoint_ctx or EndpointContext()\n            raise ResponseValidationError(\n                errors=errors,\n                body=response_content,\n                endpoint_ctx=ctx,\n            )\n        serializer = field.serialize_json if dump_json else field.serialize\n        return serializer(\n            value,\n            include=include,\n            exclude=exclude,\n            by_alias=by_alias,\n            exclude_unset=exclude_unset,\n            exclude_defaults=exclude_defaults,\n            exclude_none=exclude_none,\n        )\n\n    else:\n        return jsonable_encoder(response_content)\n","sourceCodeStart":306,"sourceCodeEnd":342,"githubUrl":"https://github.com/tiangolo/fastapi/blob/3e8d1526d83a90aaf7d6eb6dc682bf150f180b25/fastapi/routing.py#L306-L342","documentation":"ResponseValidationError raised by serialize_response (routing.py:324) when validating the endpoint's return value against the declared response_model field. The shared message comes from ValidationException.__str__ ('{n} validation error(s):\\n{errors}'); errors are the pydantic validation errors produced by field.validate(response_content, ..., loc=(\"response\",)). It surfaces as an HTTP 500 because the response the code produced does not match the response_model contract.","triggerScenarios":"An endpoint returns data that fails validation against its response_model — e.g. returning None where the model requires fields, returning an int where a str is declared, extra/missing fields with strict mode, a nested object that does not coerce to the model, or an ORM object that does not map onto the response_model.","commonSituations":"Changing the response_model without updating the endpoint return; returning a raw ORM row whose fields do not match the schema; a DB null landing on a required response field; stricter pydantic v2 validation after an upgrade; returning a wrong-shaped dict from a helper.","solutions":["Make the endpoint return data that matches response_model (correct types, required fields present).","Loosen the response_model where appropriate: Optional fields, Union, or response_model_exclude_none.","Convert ORM objects with from_attributes=True (model_config) or build the response model explicitly.","Reproduce under TestClient and read the per-field errors in the 500 response body to fix the mismatch."],"exampleFix":"// before\nclass HeroOut(BaseModel):\n    id: int\n    name: str\n    age: int  # required\n\n@app.get(\"/heroes/{i}\", response_model=HeroOut)\ndef read(i: int):\n    return {\"id\": i, \"name\": \"x\"}  # missing age -> ResponseValidationError\n\n// after\nclass HeroOut(BaseModel):\n    id: int\n    name: str\n    age: int | None = None\n\n@app.get(\"/heroes/{i}\", response_model=HeroOut)\ndef read(i: int):\n    return {\"id\": i, \"name\": \"x\"}","handlingStrategy":"validation","validationCode":"# Validate the endpoint return against response_model in a unit test\nfrom fastapi.testclient import TestClient\nfrom app import app, HeroOut\n\ndef test_read_hero_matches_response_model():\n    client = TestClient(app)\n    r = client.get(\"/heroes/1\")\n    assert r.status_code == 200\n    HeroOut.model_validate(r.json())  # raises if shape mismatches response_model","typeGuard":null,"tryCatchPattern":"from fastapi.exceptions import ResponseValidationError\nfrom fastapi.testclient import TestClient\n\nclient = TestClient(app, raise_server_exceptions=False)\nr = client.get(\"/heroes/1\")\nif r.status_code == 500 and \"validation error\" in r.text:\n    # inspect r.json()['detail'] for the failing response fields\n    print(r.text)","preventionTips":["Keep response_model and the endpoint return in lockstep; update both together.","Use Optional/Union fields where data can legitimately be absent.","Enable from_attributes on response models mapping ORM objects.","Add TestClient tests asserting each endpoint returns a valid response_model payload."],"tags":["response-model","validation","pydantic","response","fastapi"],"backgroundTag":null,"analyzedSha":"3e8d1526d83a90aaf7d6eb6dc682bf150f180b25","analyzedAt":"2026-08-11T02:34:52.986Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}