Working with Pydantic objects
When developing API endpoints with FastAPI, you'll likely 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 (ML) model. Fortunately, Pydantic provides methods to 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 to 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:
chapter4_working_pydantic_objects_01.py
person = Person( first_name="John", ...