Working with Pydantic objects
When developing API endpoints with FastAPI, you’ll probably get a lot of Pydantic model instances to handle. It’s then up to you to implement the logic to make a link between those objects and your services, such as your database or your machine learning model. Fortunately, Pydantic provides methods that make this very easy. We’ll review common use cases that will be useful for you during development.
Converting an object into a dictionary
This is probably the action you’ll perform the most on a Pydantic object: convert it into a raw dictionary that’ll be easy to send to another API or use in a database, for example. You just have to call the dict
method on the object instance.
The following example reuses the Person
and Address
models we saw in the Standard field types section of this chapter:
chapter04_working_pydantic_objects_01.py
person = Person( first_name="John",...