How do you use Pydantic in practice?
Answer
Data validation and parsing
- Define models with typed fields; Pydantic validates and coerces input (e.g. string → int, ISO string →
datetime). Invalid data raisesValidationErrorwith clear messages. Use this for request bodies, env config, and any external data.
Settings and configuration
- Use
BaseSettings(e.g.pydantic-settings) to load config from env vars and.env. You get validation, types, and optional defaults in one place. Good for API keys, DB URLs, feature flags.
API request/response schemas
- In FastAPI, declare request bodies and responses as Pydantic models. FastAPI generates OpenAPI from them and validates incoming JSON. Use
model_dump()ormodel_dump_json()for responses so output shape is consistent and documented.
Serialization control
- Use
model_dump(exclude_none=True)ormodel_dump(by_alias=True)for APIs. Usemodel_construct()when you need to build instances without validation (e.g. from DB rows you already trust). UseField(alias=...)for JSON with different key names.
Strict vs lenient
- Prefer strict types (e.g.
strnotAny) so invalid data fails fast. UseField(..., strict=True)where you want no coercion (e.g.boolonly from real booleans). Use validators orfield_validator/model_validatorfor custom rules (format, ranges, cross-field checks).
Nested and reusable models
- Compose models (nested models,
List[Item],Optional[T]) and reuse them across endpoints. Use inheritance or composition for shared fields (e.g. baseCreatedAt,Id). Keeps validation and docs in sync.
Performance
- For hot paths or very large payloads, consider
model_validate()once at the boundary and pass plain dicts or dataclasses internally, or use Pydantic’s compiled mode where available (e.g. v2 withmodel_validateand minimal re-validation).
Interview angle
- “How do you keep API and domain models separate?” - distinct models per direction: request, response and internal. Reusing one model everywhere is how internal fields leak into responses and how provider quirks reach your domain.
- “How do you handle unknown fields?” -
extra="ignore"for third-party payloads, since providers add fields routinely;extra="forbid"for your own internal APIs, where an unexpected field indicates a bug. - “How do you load configuration?” -
pydantic-settingswithBaseSettings, typed and validated at startup, usingSecretStrfor credentials so they don’t appear in logs or reprs.