PYDANTIC DTO MODELS & DATA VALIDATION

Master strongly typed contract validation and Data Transfer Object (DTO) modeling in Playwright with Python: combining APIRequestContext with Pydantic v2 BaseModels, parsing REST responses, field constraints, custom validators, nested serialization, and catching schema regressions.

πŸ“¦ 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.

1. Pydantic DTO Pipeline Architecture in Playwright
Playwright retrieves raw JSON over HTTP, which is passed into Pydantic's model_validate() method. Pydantic validates types and constraints before exposing clean, typed attributes to your tests.
DTO Pipeline & Type Safety Flow
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
Architectural Advantage: Tests interact with clean, typed Python objects instead of fragile nested string keys. If the backend breaks the contract, the test fails with an exact field path failure.
Real-Time Example 1: Basic Pydantic Model Validation with APIRequestContext
Define a standard BaseModel representing an enterprise user entity, dispatch a request with Playwright, and validate the response payload using model_validate().
Python (Basic Pydantic BaseModel DTO)
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()
Output: Pydantic DTO Validation Succeeded: User ID : 99214 (Type: int) Name : Pooja Patil Email : pooja.patil@nikita-infotech.com Role : Chief Quality Architect
Real-Time Example 2: Strict Numerical Constraints & Regex via Field()
Enforce numerical boundaries, non-empty string length restrictions, and regex format requirements using Pydantic's Field() function.
Python (Field Constraints & Pattern Matching)
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()
Output: Product DTO Validated: SKU Pattern Match : 'SKU-OPT-8841' Validated Price : β‚Ή 14999.5 Stock Units : 45
Real-Time Example 3: Nested DTOs & Array Collections
Model real-world parent-child entities by nesting Pydantic DTO models inside lists and sub-objects, ensuring type safety across deeply structured API responses.
Python (Nested Models & Collection Lists)
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()
Output: Nested Order DTO Validated: Order ID : ORD-2026-902 Item Count : 2 Calculated Total Value: β‚Ή 8400.0
Real-Time Example 4: Catching Contract Violations with ValidationError
Capture pydantic.ValidationError when an endpoint returns malformed data or altered schemas, printing clear diagnostic paths pointing to the exact offending attribute.
Python (Defensive ValidationError Diagnostics)
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()
Output: Contract Drift Detected! Total Violations: 2 Field Path : ('account_id',) Error Type : int_parsing Message : Input should be a valid integer, unable to parse string as an integer Field Path : ('secret_key',) Error Type : string_too_short Message : String should have at least 8 characters
Real-Time Example 5: Custom Domain Logic with @field_validator
Write custom Python validation methods using Pydantic's @field_validator decorator to enforce proprietary business rules (such as checking approved company domains).
Python (Custom @field_validator Rules)
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()
Output: Custom Validator Passed! Normalized Email: 'aarav.sharma@nikita-infotech.com' Custom Validator Rejected: 1 validation error for EnterpriseStaffDTO
Real-Time Example 6: Generating Outbound Request Payloads via model_dump()
Use Pydantic models not only for incoming response validation, but also as typed factories for creating outgoing request payloads via model_dump().
Python (Outbound Request Serialization)
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()
Output: Dispatched Payload from DTO: Title : 'Automated Test Run Pipeline Failure' Priority : 'HIGH' Tags : ['playwright', 'regression', 'pydantic'] Notify Manager : False
Real-Time Example 7: Handling Snake_Case & CamelCase Aliases
Modern REST APIs frequently transmit keys in camelCase (e.g. userId, firstName). Use alias_generator or Field(alias=...) to keep your Python code idiomatic snake_case.
Python (CamelCase Alias Mapping)
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()
Output: CamelCase to snake_case Mapping Verified: Python customer.account_id : 884102 Python customer.first_name : 'Rahul' Python customer.total_balance : β‚Ή 75250.0
Real-Time Example 8: Reusable Pytest Validation Helper for DTOs
Build a custom Pytest assertion helper in conftest.py that validates any Playwright APIResponse against an arbitrary Pydantic model class.
Python (Pytest DTO Assertion Helper)
# 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()
Output: Service health validated via helper: status='HEALTHY' PASSED tests/test_inventory_api.py::test_service_health
Real-Time Example 9: Pydantic DTO vs. Raw Dictionaries Reference Matrix
A comprehensive reference summary contrasting Pydantic Data Transfer Objects with traditional untyped dictionaries in Playwright Python test frameworks.
DTO Architecture Reference Matrix
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 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Define Pydantic DTO models in a dedicated dto/ directory. Ingest all Playwright API responses through model_validate() to catch schema regressions before they impact running test suites.