Modern APIs with FastAPI and Python Transcripts
Chapter: Course conclusion and review
Lecture: Review: Pydantic objects
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
The next major thing we talked about was pydantic models that are kind of like data classes, but do all sorts of cool conversions and validation.
0:08
So imagine we want to accept some kind of order. It has an item ID, a created date, a price and pages that are visited, and the
0:16
item ID, the created date and the price are all required. The item ID is an int, price is a float, date is a datetime, and then there's pages visited,
0:24
which could be a list of integers, or it could be nothing and has a default value of just an empty list. So if we want to describe our data like that,
0:32
we can do this very concisely by just deriving from the base model. Then, given some dictionary, like this
0:37
ordered JSON here, where the types are convertible too, but not exactly what we're looking for. For example, item ID is a string,
0:45
but the number "123" as a string can be converted to 123 and the pages visited
0:50
is a list of almost numbers which could be converted to numbers and so on. What we have to do is pass that data over using the "**" operator to
0:58
turn it into keyword arguments like item ID equals the string 123 and so
1:03
on. It will automatically convert that into a proper order or complain and give us a meaningful error message about what was missing,
1:10
what couldn't be converted and so on. So pydantic models are super useful on their own. But we saw that FastAPI makes really important usage of it,
1:18
right? We can pass it as arguments to functions and a stuff submitted to the API automatically gets converted.
1:24
We can use them for documentation by setting the response model, all that kind of stuff. So pydantic plays an important role in FastAPI.