backend / web frameworks / pydantic / 02_pydantic_in_practice.md

How do you use Pydantic in practice?

3 interview angles 2 min read source

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 raises ValidationError with 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() or model_dump_json() for responses so output shape is consistent and documented.

Serialization control

  • Use model_dump(exclude_none=True) or model_dump(by_alias=True) for APIs. Use model_construct() when you need to build instances without validation (e.g. from DB rows you already trust). Use Field(alias=...) for JSON with different key names.

Strict vs lenient

  • Prefer strict types (e.g. str not Any) so invalid data fails fast. Use Field(..., strict=True) where you want no coercion (e.g. bool only from real booleans). Use validators or field_validator / model_validator for 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. base CreatedAt, 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 with model_validate and 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-settings with BaseSettings, typed and validated at startup, using SecretStr for credentials so they don’t appear in logs or reprs.