python type_error ai_generated true

TypeError: Object of type UUID is not JSON serializable

ID: python/fastapi-json-encoding-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-09-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

FastAPI's default JSON encoder cannot handle UUID objects in the response.

generic

中文

FastAPI 的默认 JSON 编码器无法处理响应中的 UUID 对象。

Workarounds

  1. 90% success
    Use jsonable_encoder: from fastapi.encoders import jsonable_encoder; return jsonable_encoder(data)
  2. 85% success
    Define a custom response class that handles UUIDs: class UUIDModel(BaseModel): id: UUID

Dead Ends

Common approaches that don't work:

  1. 60% fail

    This is repetitive and error-prone if missed in some places.

  2. 50% fail

    If imported incorrectly, it may not convert UUIDs.