FastAPI Response Model via Pydantic
There are times where you don't want all the data sent back to the user
This is where you would want to define how the response looks like
In the
schemas.py
we will define the Pydantic model for the response
This will return only the fields specified in the
PostResponse
classWe will also have to define the
response_model
in the app decorator
This will still not work fully as our Pydantic model only knows how to work with dictionary's
The issue here is that when we make the query,
new_post
is a SQLAlchemy modelPydantic has no idea what to do with that, so the SQLAlchemy model has to be converted to a Pydantic model
More information about this: Click here!
To do that we will have to pass the following code
This will tell Pydantic to convert it, even if it's not a valid dict
So the new class in
schemas.py
should look like this
Now this should work and return our correct response
When retrieving a list, just passing in the normal decorator parameter
schemas.PostResponse
will not workWe need to convert this to a List with from the typing library
How it should look:
List[schemas.PostResponse]
Last updated