Chapter 5. Pydantic, Type Hints, and Models Tour

Data validation and settings management using Python type hints.

Fast and extensible, Pydantic plays nicely with your linters/IDE/brain. Define how data should be in pure, canonical Python 3.6+; validate it with Pydantic.

Samuel Colvin, developer of Pydantic

Preview

FastAPI stands largely on a Python package called Pydantic. This uses models (Python object classes) to define data structures. These are heavily used in FastAPI applications and are a real advantage when writing larger applications.

Type Hinting

It’s time to learn a little more about Python type hints.

Chapter 2 mentioned that, in many computer languages, a variable points directly to a value in memory. This requires the programmer to declare its type, so the size and bits of the value can be determined. In Python, variables are just names associated with objects, and it’s the objects that have types.

In standard programming, a variable is usually associated with the same object. If we associate a type hint with that variable, we can avoid some programming mistakes. So Python added type hinting to the language, in the standard typing module. The Python interpreter ignores the type hint syntax and runs the program as though it isn’t there. Then what’s the point?

You might treat a variable as a string in one line, and forget later and assign it an object of a different type. Although compilers for other languages would complain, Python won’t. The standard Python ...

Get FastAPI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.