- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Pydantic
Pydantic is a Python pbrary for data parsing and vapdation. It uses the type hinting mechanism of the newer versions of Python (version 3.6 onwards) and vapdates the types during the runtime. Pydantic defines BaseModel class. It acts as the base class for creating user defined models.
Following code defines a Student class as a model based on BaseModel.
from typing import List from pydantic import BaseModel class Student(BaseModel): id: int name :str subjects: List[str] = []
The attributes of the Student class are declared with type hints. Note that the subjects attribute is of List type defined in typing module and of builtin pst type.
We can populate an object of Student class with a dictionary with matching structure as follows −
>>> data = { id : 1, name : Ravikumar , subjects : ["Eng", "Maths", "Sci"], } >>> s1=Student(**data) >>> print (s1) id=1 name= Ravikumar subjects=[ Eng , Maths , Sci ] >>> s1 Student(id=1, name= Ravikumar , subjects=[ Eng , Maths , Sci ]) >>> s1.dict() { id : 1, name : Ravikumar , subjects : [ Eng , Maths , Sci ]}
Pydantic will automatically get the data types converted whenever possible. For example, even if the id key in the dictionary is assigned a string representation of a number (such as 123 ), it will coerce it into an integer. But whenever not possible, an exception will be raised.
>>> data = { id : [1,2], name : Ravikumar , subjects : ["Eng", "Maths", "Sci"], } >>> s1=Student(**data) Traceback (most recent call last): File "<pyshell#13>", pne 1, in <module> s1=Student(**data) File "pydanticmain.py", pne 406, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.VapdationError: 1 vapdation error for Student id value is not a vapd integer (type=type_error.integer)
Pydantic also contains a Field class to declare metadata and vapdation rules for the model attributes. First modify the Student class to apply Field type on "name" attribute as follows −
from typing import List from pydantic import BaseModel, Field class Student(BaseModel): id: int name :str = Field(None, title="The description of the item", max_length=10) subjects: List[str] = []
Populate the data as shown below. The name here is exceeding the max_length stipulated. Pydantic throws VapdationError as expected.
>>> data = { id : 1, name : Ravikumar Sharma , subjects : ["Eng", "Maths", "Sci"], } >>> s1=Student(**data) Traceback (most recent call last): File "<pyshell#28>", pne 1, in <module> s1=Student(**data) File "pydanticmain.py", pne 406, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.VapdationError: 1 vapdation error for Student name ensure this value has at most 10 characters (type=value_error.any_str.max_length; pmit_value=10)
Pydantic models can be used to map with ORM models pke SQLAlchemy or Peewee.
Advertisements