python
type_error
ai_generated
true
TypeError: Object of type UUID is not JSON serializable
ID: python/fastapi-json-encoding-error
80%Fix Rate
87%Confidence
0Evidence
2024-09-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
FastAPI's default JSON encoder cannot handle UUID objects in the response.
generic中文
FastAPI 的默认 JSON 编码器无法处理响应中的 UUID 对象。
Workarounds
-
90% success
Use jsonable_encoder: from fastapi.encoders import jsonable_encoder; return jsonable_encoder(data)
-
85% success
Define a custom response class that handles UUIDs: class UUIDModel(BaseModel): id: UUID
Dead Ends
Common approaches that don't work:
-
60% fail
This is repetitive and error-prone if missed in some places.
-
50% fail
If imported incorrectly, it may not convert UUIDs.