# Pydantic Models taste of a Python backend developer who wants data checked at the edges
- Use Pydantic v2 only and write new code against its API (model_validate, model_dump, field_validator), never the v1 compatibility layer. Confidence: 0.95
- Validate data at the boundaries (HTTP requests, queue messages, config, third-party responses) and pass typed models inward. Confidence: 0.90
- Keep separate models for input, output and storage (UserCreate, UserRead, UserRow) instead of one model with optional fields. Confidence: 0.90
- Set model_config = ConfigDict(extra="forbid") on request models so typos in payloads fail loudly. Confidence: 0.85
- Make value objects and events immutable with frozen=True. Confidence: 0.80
- Prefer precise types over plain str: EmailStr, HttpUrl, UUID, PositiveInt, constr with a pattern, Literal for small enums. Confidence: 0.85
- Use Annotated types with Field constraints and reuse them as named aliases (Slug = Annotated[str, Field(pattern=...)]). Confidence: 0.80
- Put single-field rules in field_validator and cross-field rules in model_validator(mode="after"); keep validators pure with no Ihttps://www.aitopic.com/O. Confidence: 0.90
- Model variants with discriminated unions on a type field instead of trying each model in order. Confidence: 0.85
- Use timezone-aware datetimes only (AwareDatetime) and reject naive ones at the boundary. Confidence: 0.85
- Store money as Decimal with fixed places, never float. Confidence: 0.95
- Load settings with pydantic-settings from environment variables, with a prefix per service and SecretStr for secrets. Confidence: 0.90
- Never return ORM objects from an API directly; convert with model_validate(obj, from_attributes=True) into a response model. Confidence: 0.85
- Keep strict mode on for internal messages and allow lax coercion only on user-facing form input. Confidence: 0.70
- Use alias_generator with to_camel when the wire format is camelCase, and keep snake_case attributes in Python. Confidence: 0.80
- Serialize with model_dump(mode="json", exclude_none=True) for APIs so dates and decimals become stable strings. Confidence: 0.75
- Use TypeAdapter for validating plain lists, dicts and unions without wrapping them in a dummy model. Confidence: 0.80
- Export JSON Schema with model_json_schema and commit it, so API clients and docs stay in sync. Confidence: 0.70
- Return validation errors as a list of field paths and messages; never leak the raw exception text to clients. Confidence: 0.85
- Avoid heavy business logic and database calls inside models; models describe shape, services do work. Confidence: 0.85
- Test models with table-driven pytest cases for valid and invalid payloads, plus a few Hypothesis property tests for parsers. Confidence: 0.70
- Run mypy or pyright with the Pydantic plugin in CI so model fields and call sites are type-checked. Confidence: 0.80
Comments & Questions (0)
No comments yet
Be the first to comment!