CodexBloom - Programming Q&A Platform

implementing JSON serialization of custom objects in Python 3.9 using FastAPI

👀 Views: 99 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
python-3.x fastapi pydantic json serialization Python

I'm sure I'm missing something obvious here, but I'm working with a question with JSON serialization of a custom class in my FastAPI application using Python 3.9. I have a class `User` that includes several fields, including a datetime field, and I'm trying to return an instance of this class from my endpoint. However, I'm working with a `TypeError` when FastAPI attempts to serialize it to JSON. The behavior message is as follows: ``` TypeError: Object of type datetime is not JSON serializable ``` Here's a snippet of my code: ```python from fastapi import FastAPI from pydantic import BaseModel from datetime import datetime app = FastAPI() class User: def __init__(self, username: str, created_at: datetime): self.username = username self.created_at = created_at @app.get("/user/{username}") async def get_user(username: str): user = User(username=username, created_at=datetime.now()) return user ``` I've looked into using Pydantic's `BaseModel`, which seems to handle serialization better, but I haven't managed to refactor my `User` class to work correctly with it. Here's what I tried: ```python class UserModel(BaseModel): username: str created_at: datetime @app.get("/user/{username}") async def get_user(username: str): user_model = UserModel(username=username, created_at=datetime.now()) return user_model ``` This change leads to a successful response, but I'm unsure how to manage additional methods I had in my original `User` class, such as a method to format the `created_at` datetime into a string in a specific format. How can I effectively combine the benefits of Pydantic serialization while retaining the methods in my class? Is there a best practice for this scenario in FastAPI?