python
type_error
ai_generated
true
TypeError: Object of type 'User' is not JSON serializable
ID: python/fastapi-typeerror-object-of-type-type-is-not-json-serializable
80%Fix Rate
87%Confidence
0Evidence
2024-03-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Returning a custom Python object directly from an endpoint without converting to a JSON-serializable format.
generic中文
直接从端点返回自定义 Python 对象,而未转换为 JSON 可序列化格式。
Workarounds
-
95% success Use a Pydantic model for the response.
from pydantic import BaseModel class UserOut(BaseModel): id: int name: str @app.get('/users/{user_id}', response_model=UserOut) async def get_user(user_id: int): user = get_user_from_db(user_id) return UserOut(id=user.id, name=user.name) -
90% success Convert the object to a dictionary manually.
@app.get('/users/{user_id}') async def get_user(user_id: int): user = get_user_from_db(user_id) return {'id': user.id, 'name': user.name}
Dead Ends
Common approaches that don't work:
-
Using json.dumps() on the object directly.
70% fail
json.dumps() also requires a serializable object; custom objects need a custom encoder.
-
Returning the object without a response model.
80% fail
FastAPI tries to serialize the object automatically but fails if it's not a dict or Pydantic model.