Validating request bodies using Pydantic models
In FastAPI, request bodies can be validated to ensure only defined data is sent. This is crucial, as it serves to sanitize request data and reduce malicious attacks’ risks. This process is known as validation.
A model in FastAPI is a structured class that dictates how data should be received or parsed. Models are created by subclassing Pydantic’s BaseModel
class.
What is Pydantic?
Pydantic is a Python library that handles data validation using Python-type annotations.
Models, when defined, are used as type hints for request body objects and request-response objects. In this chapter, we will only look at using Pydantic models for request bodies.
An example model is as follows:
from pydantic import BaseModel class PacktBook(BaseModel): id: int Name: str Publishers: str Isbn: str
In the preceding code block...