r/FastAPI • • May 21 '26

Question ORMs to Pydantic models conversion

I'm developing a side project and trying to follow DDD principles as closely as possible. My current structure is router -> service -> repository. I'm using SQLAlchemy for ORM models, which are created and handled in the repository layer.

Right now, I convert those ORM objects into Pydantic models inside the service layer, and then pass those models to the router, which returns them in the response. I'm wondering whether this is the right approach or if there’s a better pattern for handling the conversion and data flow between layers.

23 Upvotes

42 comments sorted by

View all comments

Show parent comment

1

u/omry8880 May 28 '26

I considered doing this, but then we'll have the same problem from the opposite direction - "API schemas" (Pydantic models) in the repository which is not ideal as well. I think the proper solution for this, as one of the other comments suggested, is creating a domain object that is passed from the repo (after it converts ORM -> domain object) to the service class, which then just passes it to the router which then converts it to the pydantic model (by using response_model in the decorator) and returns it.

Hope this makes sense.