{"record":{"id":"580d10f3dee5e4b5","repo":"tiangolo/fastapi","slug":"errors","errorCode":null,"errorMessage":"{errors}","messagePattern":"\\{errors\\}","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"fastapi/encoders.py","lineNumber":355,"sourceCode":"        return ENCODERS_BY_TYPE[type(obj)](obj)\n    for encoder, classes_tuple in encoders_by_class_tuples.items():\n        if isinstance(obj, classes_tuple):\n            return encoder(obj)\n    if is_pydantic_v1_model_instance(obj):\n        raise PydanticV1NotSupportedError(\n            \"pydantic.v1 models are no longer supported by FastAPI.\"\n            f\" Please update the model {obj!r}.\"\n        )\n    try:\n        data = dict(obj)\n    except Exception as e:\n        errors: list[Exception] = []\n        errors.append(e)\n        try:\n            data = vars(obj)\n        except Exception as e:\n            errors.append(e)\n            raise ValueError(errors) from e\n    return jsonable_encoder(\n        data,\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        custom_encoder=custom_encoder,\n        sqlalchemy_safe=sqlalchemy_safe,\n    )\n","sourceCodeStart":337,"sourceCodeEnd":367,"githubUrl":"https://github.com/tiangolo/fastapi/blob/3e8d1526d83a90aaf7d6eb6dc682bf150f180b25/fastapi/encoders.py#L337-L367","documentation":"ValueError raised by jsonable_encoder as a last resort (encoders.py:355). After the object matches no registered encoder, is not a pydantic v1 model, and both dict(obj) and vars(obj) raise, FastAPI collects the two caught exceptions into a list and raises ValueError(errors) from the last one. The object is simply not JSON-encodable by FastAPI's rules.","triggerScenarios":"Returning an object from an endpoint that is not a dict/list/primitive/pydantic-model/known type, and that does not support dict() or __dict__ (vars). For example a SQLAlchemy 2.x ORM object without a pydantic response_model, a custom class with __slots__ and no mapping protocol, an open file/regex/lock object, or an unserializable nested value.","commonSituations":"Returning raw SQLAlchemy/SQLModel ORM rows without a response_model that converts them; a custom dataclass-like object with __slots__; an enum or type object slipping into the response; a relationship/collection that is not JSON-coercible; a non-encodable value (datetime.tzinfo, Decimal without encoder, UUID in a raw object).","solutions":["Declare a pydantic response_model so FastAPI serializes the object through the model instead of duck-typing it.","Convert the object to a dict/list of primitives before returning (e.g. [h.model_dump() for h in rows]).","Add a custom_encoder for the specific type, or pass json_encoders via response_model.","Implement asdict()/__iter__ (to make dict(obj) work) or a normal __dict__ on the class."],"exampleFix":"// before\n@app.get(\"/widgets/{i}\")\ndef read(i: int):\n    return session.get(Widget, i)  # raw ORM object, dict()/vars() both fail\n# -> ValueError([...])\n\n// after\nclass WidgetOut(BaseModel):\n    id: int\n    name: str\n\n@app.get(\"/widgets/{i}\", response_model=WidgetOut)\ndef read(i: int):\n    return session.get(Widget, i)","handlingStrategy":"try-catch","validationCode":"# Verify an object is jsonable_encoder-friendly before returning it\nfrom fastapi.encoders import jsonable_encoder\n\ndef safe(obj):\n    try:\n        jsonable_encoder(obj)\n        return obj\n    except Exception:\n        # convert ORM/dataclass to dict before returning\n        if hasattr(obj, \"model_dump\"):\n            return obj.model_dump()\n        if hasattr(obj, \"__dict__\"):\n            return vars(obj)\n        raise","typeGuard":"def is_jsonable(obj) -> bool:\n    try:\n        jsonable_encoder(obj)\n    except Exception:\n        return False\n    return True","tryCatchPattern":"from fastapi.encoders import jsonable_encoder\ntry:\n    payload = jsonable_encoder(result)\nexcept ValueError:\n    payload = [r.model_dump() for r in result] if isinstance(result, list) else result.model_dump()","preventionTips":["Always declare a pydantic response_model for ORM/data sources.","Return model_dump()/dict() of raw objects instead of ORM rows.","Add custom encoders for niche types (Decimal, UUID, enum).","Write a TestClient test that hits each endpoint and asserts a 200 JSON body."],"tags":["encoding","serialization","response-model","json","fastapi"],"backgroundTag":null,"analyzedSha":"3e8d1526d83a90aaf7d6eb6dc682bf150f180b25","analyzedAt":"2026-08-11T02:34:52.986Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}