Recipe
This recipe shows how to validate data structures using Zod (TypeScript) or Pydantic (Python), including synchronous and asynchronous validation patterns.TypeScript: Zod version
3.22+ is supported, which provides the zod/v3
export path required by libraries like json-schema-to-zod. Python: Examples
target Pydantic v2 (pydantic>=2.0).Code example
Synchronous validation
TypeScript
Asynchronous validation
TypeScript
Pydantic validators run synchronously. For async checks (like database lookups), validate the data structure first with
model_validate(), then run async logic afterward—as shown above.Comparison: TypeScript vs Python
| Pattern | TypeScript (Zod) | Python (Pydantic) |
|---|---|---|
| Safe validation (no throw) | safeParse() → { success, data, error } | try/except ValidationError |
| Strict validation (throws) | parse() → throws ZodError | model_validate() → raises ValidationError |
| Async validation | .safeParseAsync() / .refine(async fn) | Validate sync first, then run async checks |
| Skip validation | N/A | model_construct() |
| Access errors | error.format() / error.issues | e.errors() → list of dicts |
Common pitfalls
Date parsing — Pydantic automatically parses ISO 8601 strings intodatetime objects. Watch out for timezone-aware vs. naive datetimes: "2024-01-01T00:00:00Z" becomes timezone-aware, while "2024-01-01T00:00:00" is naive. Mixing them raises an error.
Optional fields — Mark optional fields with Optional[X] = None (or X | None = None in Python 3.10+). A field typed as Optional[X] without a default is still required on input.
Custom validators — Use @field_validator for single-field checks and @model_validator(mode='after') for cross-field checks:
Related
TypeScript SDK
Learn about the Intuned Browser SDK for TypeScript.
Python SDK
Learn about the Intuned Browser SDK for Python.