Quick Start¶
Get up and running with pydantic-marshmallow in 5 minutes.
Step 1: Define a Pydantic Model¶
from pydantic import BaseModel, Field, EmailStr
class User(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: EmailStr
age: int = Field(ge=0, le=150)
Step 2: Create a Marshmallow Schema¶
There are three ways to create a schema:
Step 3: Load and Validate Data¶
# Valid data
user = schema.load({
"name": "Alice",
"email": "alice@example.com",
"age": 30
})
print(type(user)) # <class 'User'>
print(user.name) # "Alice"
Step 4: Handle Validation Errors¶
from marshmallow import ValidationError
try:
user = schema.load({
"name": "", # Too short
"email": "invalid", # Not an email
"age": -5 # Negative
})
except ValidationError as e:
print(e.messages)
# {
# 'name': ['String should have at least 1 character'],
# 'email': ['value is not a valid email address'],
# 'age': ['Input should be greater than or equal to 0']
# }
Step 5: Serialize Data¶
# Serialize a Pydantic model instance
data = schema.dump(user)
# {"name": "Alice", "email": "alice@example.com", "age": 30}
# Serialize to JSON string
json_str = schema.dumps(user)
Next Steps¶
- Basic Usage - Learn more about core features
- Hooks & Validators - Add custom validation logic
- Ecosystem Integration - Use with Flask, webargs, apispec