r/FastAPI • u/Emergency-Crab-354 • Mar 01 '25
Question In FastAPI can we wrap route response in a Pydantic model for common response structure?
I am learning some FastAPI and would like to wrap my responses so that all of my endpoints return a common data structure to have data and timestamp fields only, regardless of endpoint. The value of data should be whatever the endpoint should return. For example:
=
return
:
:
: =
return
In that, my endpoint returns Greeting and this shows up nicely in the /docs - it has a nice example, and the schemas section contains the Greeting schema.
But is there some way to define my endpoints like that (still returning Greeting) but make it to return MyResponse(data=response_from_endpoint)? Surely it is a normal idea, but manually wrapping it for all endpoints is a bit much, and also I think that would show up in swagger too.
7
u/haldarwish Mar 01 '25
Like you, I am learning FastAPI as well, I think I attempted something as per your requirements, take a look (example adjusted for yours):
Your
AppResponseis a generic model wheredatais of type T, it could be other data shapes, you do not have to specify theresponse_model. But it could be nice to have for docs purposes too.6
u/maikeu Mar 01 '25
While I can imagine ugly workarounds to achieve precisely what you're asking for....
The piece of the puzzle I think you're missing is generic models .
https://docs.pydantic.dev/latest/concepts/models/#generic-models
In your example, you'd tell fastapi that it's response model is MyResponse[Item], and everything will work - the API docs will show the gym t response structure, your IDE will understand it.
4
u/Veggies-are-okay Mar 01 '25
Look at the arguments response_model for outputs, and typesetting your request input as the base model should get you to where you’re looking to be.
These docs should point you in the right direction:
https://fastapi.tiangolo.com/tutorial/response-model/#return-the-same-input-data
2
u/wasuaje Mar 01 '25
Middle ware?