# TypeError: Object of type 'User' is not JSON serializable

- **ID:** `python/fastapi-typeerror-object-of-type-type-is-not-json-serializable`
- **Domain:** python
- **Category:** type_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Returning a custom Python object directly from an endpoint without converting to a JSON-serializable format.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **Use a Pydantic model for the response.** (95% success)
   ```
   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)
   ```
2. **Convert the object to a dictionary manually.** (90% success)
   ```
   @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

- **Using json.dumps() on the object directly.** — json.dumps() also requires a serializable object; custom objects need a custom encoder. (70% fail)
- **Returning the object without a response model.** — FastAPI tries to serialize the object automatically but fails if it's not a dict or Pydantic model. (80% fail)
