Summary of "Pydantic Crash Course | Data Validation in Python | CampusX"

High-level summary


Step-by-step methodology / practical patterns

  1. Install

    • Use Pydantic v2 (recommended over v1).
  2. Create a model (the schema)

    • Subclass pydantic.BaseModel (for example: class Patient(BaseModel): ...).
    • Declare fields with Python types: name: str, age: int, weight: float, married: bool, etc.
    • Use typing annotations for complex containers (e.g., from typing import List, Dict, Optional, Annotated).
      • Examples: allergies: List[str], contact_details: Dict[str, str].
  3. Instantiate / validate raw input

    • Build a raw dict with incoming data and instantiate the model by unpacking: patient = Patient(**raw_dict).
    • On instantiation, Pydantic:
      • Validates types and values.
      • Performs automatic type coercion where appropriate (e.g., "30"30) unless strict mode is enabled.
      • Raises ValidationError on failure.
  4. Use models in your API or business logic

    • Accept validated model instances as function parameters, e.g.:
      • def insert_patient(patient: Patient): ...
    • This centralizes validation and avoids repeating checks.
  5. Required vs Optional fields and defaults

    • Fields are required by default.
    • Make fields optional with Optional[T] and a default of None, e.g. allergies: Optional[List[str]] = None.
    • Set default values directly in the model, e.g. married: bool = False.
  6. Built-in / specialized types

    • Use Pydantic’s specialized types for common validation: EmailStr, AnyUrl (or equivalents) to validate email/URL formats automatically.
  7. Custom constraints and metadata — Field + Annotated

    • Use Field(...) to impose constraints and set defaults (gt, lt, ge, le, max_length, etc.).
      • Numeric constraints: Field(gt=0) or Field(ge=0, le=120).
      • String/list constraints: Field(max_length=50) or Field(max_length=5) for list length.
    • Use Annotated[type, Field(...)] to attach metadata such as title, description, and examples (useful for docs like FastAPI).
  8. Strict mode (no coercion)

    • Use Field(..., strict=True) (or Annotated + Field) to prevent automatic coercion so strings like "75.2" won’t be accepted for a float field.
  9. Field validators (single-field)

    • Use @field_validator for per-field custom logic (validation or transformation).
    • Modes:
      • mode='before' (pre): validator receives raw input before type coercion.
      • mode='after' (default): runs after Pydantic coerces types.
    • Example uses:
      • Custom domain check for email (raise error for disallowed domains).
      • Transformations like name -> name.upper().
  10. Model validators (cross-field) - Use @model_validator to validate or enforce rules that depend on multiple fields. - Example: if age > 60 then contact_details must contain an 'emergency' phone number; raise an error otherwise.

  11. Computed fields (derived/calculated) - Use @computed_field (plus a property) to expose derived values computed from other fields (e.g., BMI from weight and height). - Computed fields are exposed on the model but are not provided by the user.

  12. Nested models - Build separate models for logical sub-objects and use them as field types: - Example: class Address(BaseModel): city: str; state: str; pincode: str then address: Address in Patient. - Benefits: structure, reusability, readability, and built-in validation of nested structures.

  13. Exporting model data - model.model_dump() → Python dict. - model.model_dump_json() → JSON string. - Control output with include / exclude and exclude_unset to omit fields not explicitly set.

  14. Error handling - Pydantic raises structured ValidationError instances when validation fails — catch and handle them in your application.

  15. Practical notes - This pattern reduces boilerplate and centralizes validation; especially useful with FastAPI, data pipelines, ML workflows, file parsing, and other production systems. - Pydantic v2 is faster (parts rewritten in Rust) and is the recommended version.


Key concepts (quick recap)


Common example patterns


Limitations / caveats


Speakers / sources featured

Category ?

Educational


Share this summary


Is the summary off?

If you think the summary is inaccurate, you can reprocess it with the latest model.

Video