How to Replace pydantic.json.ENCODERS_BY_TYPE[ObjectId] = str in Pydantic 2.x.x and FastAPI 1.x.x Versions?

After Pydantic’s migration to a new core, they have removed the usage of pydantic.json.ENCODERS_BY_TYPE[ObjectId] = str. Despite all my attempts and research, I haven’t been able to find what to replace it with.

I wanted to serialize ObjectId using native FastAPI methods, but this approach doesn’t seem to work in the new versions.

Please try to import this instead
from pydantic.v1.json import ENCODERS_BY_TYPE

then continue with your code ENCODERS_BY_TYPE[ObjectId] = str

Leave a Comment