π¦ Type-Safe Contract Architecture with Pydantic DTOs
Parsing raw untyped Python dictionaries from API responses (like response.json()["data"][0]["price"]) creates brittle tests vulnerable to KeyError exceptions and silent type mismatches. Data Transfer Objects (DTOs) define explicit, strongly typed contracts for data entering and leaving your test framework. By integrating Pydantic v2 with Playwright's APIRequestContext, automation engineers can parse JSON payloads directly into validated Python class models. Pydantic guarantees strict runtime type coercion, enforces field constraints (such as positive numbers, regex patterns, and email formats), provides autocompletion inside IDEs, and raises clear, descriptive ValidationError diagnostics when backend services introduce breaking contract changes.
model_validate() method. Pydantic validates types and constraints before exposing clean, typed attributes to your tests.
RAW UNTYPED DICTIONARY PATTERN (Brittle, No Autocomplete, Prone to Runtime Errors):
[ response.json() ] βββΊ {"id": "101", "total": "invalid"} βββΊ assert response["total"] > 0 (Crash!)
PYDANTIC DTO VALIDATION PIPELINE (Type-Safe, Self-Documenting, Contract-Enforced):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1. Playwright HTTP Request via APIRequestContext β
β response = api.get("/api/v1/orders/101") β
β raw_payload = response.json() β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 2. Pydantic DTO Ingestion: OrderResponseDTO.model_validate(raw_payload) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β * Type Coercion: Ensures 'id' is int, 'created_at' is datetime β
β * Field Rules: Field(gt=0), EmailStr, Pattern regex β
β * Custom Validators: @field_validator checks business logic rules β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββ
βΌ βΌ
β
VALID DTO INSTANCE β CONTRACT DRIFT DETECTED
order.id, order.total_inr pydantic.ValidationError:
IDE Autocompletion Enabled Input should be greater than 0
BaseModel representing an enterprise user entity, dispatch a request with Playwright, and validate the response payload using model_validate().
from pydantic import BaseModel, EmailStr
from playwright.sync_api import sync_playwright, expect
class UserProfileDTO(BaseModel):
"""Data Transfer Object representing a validated user profile."""
user_id: int
full_name: str
email: EmailStr
is_active: bool
role: str
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
payload = {
"user_id": 99214,
"full_name": "Pooja Patil",
"email": "pooja.patil@nikita-infotech.com",
"is_active": True,
"role": "Chief Quality Architect"
}
# Dispatch request via Playwright
response = api.post("/post", data=payload)
expect(response).to_be_ok()
raw_json = response.json()["json"]
# Ingest and validate using Pydantic v2
user = UserProfileDTO.model_validate(raw_json)
print("Pydantic DTO Validation Succeeded:")
print(f" User ID : {user.user_id} (Type: {type(user.user_id).__name__})")
print(f" Name : {user.full_name}")
print(f" Email : {user.email}")
print(f" Role : {user.role}")
assert user.user_id == 99214
assert user.is_active is True
api.dispose()
Field() function.
from pydantic import BaseModel, Field
from playwright.sync_api import sync_playwright, expect
class ProductCatalogDTO(BaseModel):
"""DTO enforcing inventory code formats and pricing boundaries."""
sku: str = Field(pattern=r"^SKU-[A-Z]{3}-\d{4}$")
name: str = Field(min_length=3, max_length=100)
price_inr: float = Field(gt=0, description="Price must be strictly positive")
stock_count: int = Field(ge=0, le=10000)
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
product_payload = {
"sku": "SKU-OPT-8841",
"name": "Industrial IoT Gateway",
"price_inr": 14999.50,
"stock_count": 45
}
response = api.post("/post", data=product_payload)
expect(response).to_be_ok()
# Validate against constraints
product = ProductCatalogDTO.model_validate(response.json()["json"])
print("Product DTO Validated:")
print(f" SKU Pattern Match : '{product.sku}'")
print(f" Validated Price : βΉ {product.price_inr}")
print(f" Stock Units : {product.stock_count}")
assert product.sku.startswith("SKU-OPT")
assert product.price_inr > 10000
api.dispose()
from typing import List
from pydantic import BaseModel, Field
from playwright.sync_api import sync_playwright, expect
class OrderItemDTO(BaseModel):
item_id: str
quantity: int = Field(gt=0)
unit_price: float = Field(gt=0)
class OrderInvoiceDTO(BaseModel):
order_id: str
customer_name: str
items: List[OrderItemDTO] = Field(min_length=1)
is_settled: bool
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
complex_order = {
"order_id": "ORD-2026-902",
"customer_name": "Nikita Infotech Systems",
"items": [
{"item_id": "MOD-1", "quantity": 3, "unit_price": 1200.0},
{"item_id": "MOD-2", "quantity": 1, "unit_price": 4800.0}
],
"is_settled": True
}
response = api.post("/post", data=complex_order)
expect(response).to_be_ok()
invoice = OrderInvoiceDTO.model_validate(response.json()["json"])
print("Nested Order DTO Validated:")
print(f" Order ID : {invoice.order_id}")
print(f" Item Count : {len(invoice.items)}")
total_val = sum(item.quantity * item.unit_price for item in invoice.items)
print(f" Calculated Total Value: βΉ {total_val}")
assert invoice.items[0].quantity == 3
assert total_val == 8400.0
api.dispose()
pydantic.ValidationError when an endpoint returns malformed data or altered schemas, printing clear diagnostic paths pointing to the exact offending attribute.
from pydantic import BaseModel, Field, ValidationError
from playwright.sync_api import sync_playwright
class AccountCredentialsDTO(BaseModel):
account_id: int
secret_key: str = Field(min_length=8)
tier: str
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Deliberate backend regression: 'secret_key' too short and 'account_id' is non-numeric
corrupted_data = {
"account_id": "NOT_AN_INT",
"secret_key": "short",
"tier": "Gold"
}
try:
AccountCredentialsDTO.model_validate(corrupted_data)
except ValidationError as err:
print("Contract Drift Detected! Total Violations:", err.error_count())
for e in err.errors():
print(f" Field Path : {e['loc']}")
print(f" Error Type : {e['type']}")
print(f" Message : {e['msg']}")
api.dispose()
@field_validator decorator to enforce proprietary business rules (such as checking approved company domains).
from pydantic import BaseModel, field_validator
from playwright.sync_api import sync_playwright, expect
class EnterpriseStaffDTO(BaseModel):
staff_id: str
company_email: str
@field_validator("company_email")
@classmethod
def validate_corporate_domain(cls, value: str) -> str:
allowed_domain = "@nikita-infotech.com"
if not value.endswith(allowed_domain):
raise ValueError(f"Email must belong to corporate domain: '{allowed_domain}'")
return value.lower()
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
valid_payload = {"staff_id": "STF-101", "company_email": "AARAV.SHARMA@NIKITA-INFOTECH.COM"}
res = api.post("/post", data=valid_payload)
expect(res).to_be_ok()
staff = EnterpriseStaffDTO.model_validate(res.json()["json"])
print(f"Custom Validator Passed! Normalized Email: '{staff.company_email}'")
# Validate rejection on unapproved domain
try:
EnterpriseStaffDTO(staff_id="STF-102", company_email="user@gmail.com")
except ValueError as val_err:
print("Custom Validator Rejected:", str(val_err).splitlines()[0])
api.dispose()
model_dump().
from typing import Optional
from pydantic import BaseModel, Field
from playwright.sync_api import sync_playwright, expect
class CreateTicketRequestDTO(BaseModel):
"""DTO defining the request body for creating a ticket."""
title: str = Field(min_length=5)
priority: str = Field(default="MEDIUM")
tags: list[str] = Field(default_factory=list)
notify_manager: Optional[bool] = False
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# 1. Instantiate strongly typed request object
ticket_dto = CreateTicketRequestDTO(
title="Automated Test Run Pipeline Failure",
priority="HIGH",
tags=["playwright", "regression", "pydantic"]
)
# 2. Serialize to Python dictionary via model_dump() and dispatch
response = api.post("/post", data=ticket_dto.model_dump())
expect(response).to_be_ok()
dispatched_json = response.json()["json"]
print("Dispatched Payload from DTO:")
print(f" Title : '{dispatched_json['title']}'")
print(f" Priority : '{dispatched_json['priority']}'")
print(f" Tags : {dispatched_json['tags']}")
print(f" Notify Manager : {dispatched_json['notify_manager']}")
assert dispatched_json["priority"] == "HIGH"
api.dispose()
camelCase (e.g. userId, firstName). Use alias_generator or Field(alias=...) to keep your Python code idiomatic snake_case.
from pydantic import BaseModel, Field
from playwright.sync_api import sync_playwright, expect
class CustomerAccountDTO(BaseModel):
# Map camelCase JSON keys from server to snake_case Python attributes
account_id: int = Field(alias="accountId")
first_name: str = Field(alias="firstName")
total_balance: float = Field(alias="totalBalance")
class Config:
populate_by_name = True
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# API response returning camelCase keys
backend_camel_response = {
"accountId": 884102,
"firstName": "Rahul",
"totalBalance": 75250.00
}
res = api.post("/post", data=backend_camel_response)
expect(res).to_be_ok()
customer = CustomerAccountDTO.model_validate(res.json()["json"])
print("CamelCase to snake_case Mapping Verified:")
print(f" Python customer.account_id : {customer.account_id}")
print(f" Python customer.first_name : '{customer.first_name}'")
print(f" Python customer.total_balance : βΉ {customer.total_balance}")
assert customer.account_id == 884102
api.dispose()
conftest.py that validates any Playwright APIResponse against an arbitrary Pydantic model class.
# content of conftest.py
from typing import Type, TypeVar
import pytest
from pydantic import BaseModel, ValidationError
from playwright.sync_api import APIResponse
T = TypeVar("T", bound=BaseModel)
def validate_response_as(response: APIResponse, model_class: Type[T]) -> T:
"""Helper that verifies response is OK and parses it into given Pydantic model."""
assert response.ok, f"Request failed: HTTP {response.status} - {response.text()}"
try:
return model_class.model_validate(response.json())
except ValidationError as err:
pytest.fail(f"DTO Contract Validation Failed for {model_class.__name__}:\n{err}")
# content of test_inventory_api.py
class HealthStatusDTO(BaseModel):
status: str
uptime_seconds: float
def test_service_health(playwright):
api = playwright.request.new_context(base_url="https://httpbin.org")
response = api.post("/post", data={"status": "HEALTHY", "uptime_seconds": 3600.5})
# Wrapper helper unpacks httpbin payload and validates
payload_stub = type('Obj', (object,), {
'ok': response.ok,
'status': response.status,
'json': lambda: response.json()["json"],
'text': response.text
})
health = validate_response_as(payload_stub, HealthStatusDTO)
assert health.status == "HEALTHY"
print(f"Service health validated via helper: status='{health.status}'")
api.dispose()
PYDANTIC DTO VS. UNTYPED DICTIONARY ARCHITECTURAL MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββ
β Architectural Dimension β Pydantic v2 DTO Model β Untyped Dict (response.json()) β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββ€
β Type Enforcement β Strict runtime type checking & coercion β None (values can be any unexpected type) β
β IDE Developer Experience β Full autocompletion (user.user_id) β Blind string index lookup user["user_id"]β
β Contract Drift Detection β Instant ValidationError with field path β Silent passes or obscure KeyError crashesβ
β Field Constraints β Field(gt=0, pattern=r"...", min_length=2)β Requires dozens of manual assert lines β
β Nested Structure Validation β Automatic recursive child validation β Deep nested loops and brittle indexing β
β Alias Mapping β Built-in camelCase to snake_case mapping β Manual key renaming code required β
β Outbound Payload Factory β model_dump() generates valid JSON bodies β Manually assembled dictionary structures β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ