Reader small image

You're reading from  Building Data Science Applications with FastAPI

Product typeBook
Published inOct 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801079211
Edition1st Edition
Languages
Concepts
Right arrow
Author (1)
François Voron
François Voron
author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron

Right arrow

Adding custom data validation with Pydantic

Up to now, we've seen how to apply basic validation to our models, through the Field arguments or the custom types provided by Pydantic. In a real-world project, though, you'll probably need to add your own custom validation logic for your specific case. Pydantic allows this by defining validators, which are methods on the model that can be applied at a field level or an object level.

Applying validation at a field level

This is the most common case: have a validation rule for a single field. To define it in Pydantic, we'll just have to write a static method on our model and decorate it with the validator decorator. As a reminder, decorators are syntactic sugar, allowing the wrapping of a function or a class with common logic, without compromising readability.

The following example checks a birth date by verifying that the person is not more than 120 years old:

chapter4_custom_validation_01.py

from datetime import...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Building Data Science Applications with FastAPI
Published in: Oct 2021Publisher: PacktISBN-13: 9781801079211

Author (1)

author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron