Introduction to Pydantic Classes
Pydantic is a data validation and parsing library that leverages Python's type annotations. It is most known for enabling the creation of "models" or "schemas" with strict data types, ensuring your data is both clean and structured. With Pydantic, you can define classes that automatically validate incoming data, parse types, and even handle custom data transformations.
Basic Example
Here’s a simple example of how Pydantic can help you define and validate data models:
from pydantic import BaseModel, EmailStr
class User(BaseModel):
id: int
name: str
email: EmailStr
is_active: bool = True # default value
# Input data
user_data = {'id': 1, 'name': 'John Doe', 'email': 'john@example.com'}
# Creating and validating the model
user = User(**user_data)
print(user)
This will automatically validate that the id
is an integer, email
is a valid email, and name
is a string. If the input doesn’t match these types, Pydantic will raise a ValidationError
.
1. Validating API Payloads
One of the most common uses of Pydantic is validating incoming payloads for APIs. It can quickly ensure that data coming from a frontend or another service adheres to the expected format.
Example:
from pydantic import BaseModel
class CreateUserRequest(BaseModel):
username: str
password: str
email: EmailStr
# Simulated API payload
payload = {
"username": "new_user",
"password": "secure_pass",
"email": "new_user@example.com"
}
user_request = CreateUserRequest(**payload)
This ensures that all required fields are present and correctly typed, preventing potential security vulnerabilities or bugs due to malformed data.
2. Database Interaction & ORM Integration
Pydantic is often used alongside ORMs like SQLAlchemy. You can create Pydantic models to validate data before inserting it into the database or converting database records into structured Pydantic objects.
Example:
from pydantic import BaseModel
class UserSchema(BaseModel):
id: int
username: str
email: EmailStr
is_active: bool
# Convert database row to Pydantic model
db_record = {"id": 1, "username": "john_doe", "email": "john@example.com", "is_active": True}
user = UserSchema(**db_record)
3. File Upload Validation
Pydantic can be used to validate files uploaded through APIs, ensuring they conform to specific size, type, or format constraints.
Example:
from pydantic import BaseModel, conint
class FileUpload(BaseModel):
file_name: str
file_size: conint(lt=5 * 1024 * 1024) # Maximum file size: 5MB
# Simulated file metadata
file_info = {"file_name": "document.pdf", "file_size": 4500000}
file_upload = FileUpload(**file_info)
This validates that the file size does not exceed 5MB.
4. Configuration Management
Pydantic can validate configuration files, such as JSON or environment variables. It's excellent for ensuring your app's configuration is clean and correct.
Example:
from pydantic import BaseSettings
class AppConfig(BaseSettings):
app_name: str
debug: bool = False
port: int
config = AppConfig(app_name="MyApp", debug=True, port=8000)
print(config)
Using BaseSettings
allows you to manage configuration with automatic environment variable loading and validation.
5. Form Data Validation in Web Applications
When building forms in web applications, Pydantic helps validate the submitted data.
Example:
from pydantic import BaseModel, constr
class SignUpForm(BaseModel):
username: constr(min_length=3, max_length=20)
password: constr(min_length=8)
email: EmailStr
form_data = {"username": "newuser", "password": "strongpassword", "email": "user@example.com"}
signup = SignUpForm(**form_data)
This ensures fields like username
, password
, and email
are valid before proceeding with user registration.
6. Command-Line Argument Parsing
Pydantic can be combined with command-line argument parsers to validate and cleanly handle command-line inputs.
Example:
import argparse
from pydantic import BaseModel
class CLIArgs(BaseModel):
file_path: str
verbosity: int = 1 # default level
parser = argparse.ArgumentParser()
parser.add_argument("file_path")
parser.add_argument("--verbosity", type=int)
args = parser.parse_args()
cli_args = CLIArgs(file_path=args.file_path, verbosity=args.verbosity)
This validates the command-line inputs for type and format before processing them in the script.
7. Data Transformation & Parsing
Pydantic not only validates data but can also perform transformations, such as converting string dates into datetime
objects automatically.
Example:
from pydantic import BaseModel
from datetime import datetime
class Event(BaseModel):
name: str
event_date: datetime
data = {"name": "Conference", "event_date": "2024-10-15T15:30:00"}
event = Event(**data)
print(event.event_date) # Outputs a datetime object
This converts the ISO-formatted date string into a datetime
object automatically.
8. Unit Testing with Pydantic
In testing, Pydantic can be used to mock or validate the structure of test inputs.
Example:
from pydantic import BaseModel
class TestData(BaseModel):
input: int
expected_output: int
test_case = TestData(input=5, expected_output=25)
Using this approach ensures that your test inputs are correctly formatted before running the tests.
9. Handling External API Responses
When consuming external APIs, Pydantic can validate the response structure and types, ensuring you're working with clean data.
Example:
from pydantic import BaseModel
class WeatherResponse(BaseModel):
temperature: float
humidity: int
city: str
response_data = {"temperature": 22.5, "humidity": 56, "city": "Berlin"}
weather = WeatherResponse(**response_data)
This validates the structure of the API response and ensures all necessary fields are present and properly typed.
10. Nested Data Structures
Pydantic supports complex, nested data models, making it easy to work with hierarchical data.
Example:
from pydantic import BaseModel
class Address(BaseModel):
street: str
city: str
zipcode: str
class UserProfile(BaseModel):
name: str
age: int
address: Address
profile_data = {
"name": "Alice",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Wonderland",
"zipcode": "12345"
}
}
profile = UserProfile(**profile_data)
This allows you to manage deeply nested JSON or database records with ease.
Conclusion
Pydantic is a versatile and powerful tool for any Python developer dealing with structured data. From API payload validation to nested data models and configuration management, it simplifies data handling and enhances reliability.