Middle
What data can be validated using Pydantic?
sobes.tech AI
Answer from AI
Pydantic allows validation of the following data types:
- Standard Python types:
int,float,str,bool,list,dict,tuple,set,bytes,bytearray. - Nested Pydantic models: Enables creating complex structures.
- Enumerations (Enums): Restricts possible values to a predefined set.
- Dates and times:
datetime,date,time,timedelta. - UUIDs: For globally unique identifiers.
- URL: With format validation.
- IPv4/IPv6 addresses: With format validation.
- Email addresses: With basic format validation.
- Types from the
typingmodule:Optional,Union,Literal,Final,Annotated, and others. - Custom types: By defining validators.
Validation example:
from pydantic import BaseModel, Field, EmailStr
from typing import List, Optional
from datetime import date
class User(BaseModel):
user_id: int = Field(gt=0) // Integer greater than 0
username: str = Field(min_length=3) // String with minimum 3 characters
email: EmailStr // Valid email string
is_active: bool = True // Boolean (default True)
registration_date: date // Date
tags: Optional[List[str]] = None // Optional list of strings
class Product(BaseModel):
product_id: int
name: str
price: float = Field(ge=0) // Number with decimal, greater than or equal to 0