{
  "id": "python/fastapi-typeerror-object-of-type-type-is-not-json-serializable",
  "signature": "TypeError: Object of type 'User' is not JSON serializable",
  "signature_zh": "TypeError: 类型 'User' 的对象不是 JSON 可序列化的",
  "regex": "TypeError:\\ Object\\ of\\ type\\ 'User'\\ is\\ not\\ JSON\\ serializable",
  "domain": "python",
  "category": "type_error",
  "subcategory": null,
  "root_cause": "Returning a custom Python object directly from an endpoint without converting to a JSON-serializable format.",
  "root_cause_type": "generic",
  "root_cause_zh": "直接从端点返回自定义 Python 对象，而未转换为 JSON 可序列化格式。",
  "versions": [
    {
      "version": "3.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "Using json.dumps() on the object directly.",
      "why_fails": "json.dumps() also requires a serializable object; custom objects need a custom encoder.",
      "fail_rate": 0.7,
      "condition": "",
      "sources": []
    },
    {
      "action": "Returning the object without a response model.",
      "why_fails": "FastAPI tries to serialize the object automatically but fails if it's not a dict or Pydantic model.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "Use a Pydantic model for the response.",
      "success_rate": 0.95,
      "how": "from pydantic import BaseModel\nclass UserOut(BaseModel):\n    id: int\n    name: str\n\n@app.get('/users/{user_id}', response_model=UserOut)\nasync def get_user(user_id: int):\n    user = get_user_from_db(user_id)\n    return UserOut(id=user.id, name=user.name)",
      "condition": "",
      "sources": []
    },
    {
      "action": "Convert the object to a dictionary manually.",
      "success_rate": 0.9,
      "how": "@app.get('/users/{user_id}')\nasync def get_user(user_id: int):\n    user = get_user_from_db(user_id)\n    return {'id': user.id, 'name': user.name}",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.87,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-03-30",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}