# TypeError: Object of type datetime is not JSON serializable

- **ID:** `python/fastapi-json-encode-error`
- **Domain:** python
- **Category:** data_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

FastAPI 路径操作返回了 Python datetime 对象，但 JSON 编码器无法处理

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.9 | active | — | — |
| 3.10 | active | — | — |

## Workarounds

1. **使用 Pydantic 模型并定义字段类型** (95% success)
   ```
   from pydantic import BaseModel
class Item(BaseModel):
    created_at: datetime
    class Config:
        json_encoders = {datetime: lambda v: v.isoformat()}
   ```
2. **在返回前手动转换** (90% success)
   ```
   return {'created_at': datetime.now().isoformat()}
   ```

## Dead Ends

- **手动将 datetime 转为字符串但忽略时区** — 可能导致时区信息丢失 (60% fail)
- **使用 json.dumps 并设置默认参数** — FastAPI 使用自己的 JSON 编码器，自定义可能被覆盖 (70% fail)
