home / skills / jiatastic / open-python-skills / pydantic

pydantic skill

/skills/pydantic

This skill helps you implement data validation and serialization with Pydantic, improving input handling and JSON schema generation for Python backends.

npx playbooks add skill jiatastic/open-python-skills --skill pydantic

Review the files below or copy the command above to add this skill to your agents.

Files (3)
SKILL.md
1.6 KB
---
name: pydantic
description: >
  Pydantic models and validation. Use when: (1) Defining schemas,
  (2) Validating input/output, (3) Generating JSON schema.
---

# pydantic

Type-driven validation and serialization using Pydantic models.

## Overview

Pydantic validates data using Python type hints and provides rich serialization via `model_dump()` and JSON schema output.

## When to Use

- Validating request/response payloads
- Normalizing untrusted input
- Generating JSON schema for docs

## Quick Start

```bash
uv pip install pydantic
```

```python
from pydantic import BaseModel

class User(BaseModel):
    id: int
    email: str

user = User(id=1, email="[email protected]")
```

## Core Patterns

1. **Typed fields**: strict schema definitions.
2. **Field validators**: custom validation logic.
3. **Model validators**: cross-field checks.
4. **Serialization**: `model_dump()` and `model_dump_json()`.
5. **Settings**: environment-driven config via `BaseSettings`.

## Example: field_validator

```python
from pydantic import BaseModel, field_validator

class Model(BaseModel):
    name: str

    @field_validator("name")
    @classmethod
    def ensure_not_empty(cls, v: str):
        if not v:
            raise ValueError("name required")
        return v
```

## Example: model_validate + model_dump

```python
from pydantic import BaseModel

class Model(BaseModel):
    foo: int

model = Model.model_validate({"foo": 1})
print(model.model_dump())
```

## Troubleshooting

- **Coercion surprises**: use strict types if needed
- **Slow validators**: keep them minimal
- **Mutable defaults**: use `default_factory`

## References

- https://docs.pydantic.dev/

Overview

This skill provides Pydantic-driven models and validation helpers for Python backends. I focus on type-driven validation, safe serialization, and JSON Schema generation to make request/response handling and configuration robust. The goal is predictable data shapes, clear errors, and easy integration with frameworks like FastAPI.

How this skill works

I define schemas as Python classes that inherit from BaseModel and use type hints to validate and coerce incoming data. Field and model validators let you add custom checks and cross-field logic, while model_dump and model_dump_json produce clean serialized output. BaseSettings support environment-driven configuration and Pydantic can emit JSON Schema for documentation or contract validation.

When to use it

  • Validating and normalizing API request and response payloads.
  • Defining clear data contracts for services and background jobs.
  • Generating JSON Schema for docs, client generation, or validation tooling.
  • Loading typed configuration from environment variables or files.
  • Protecting endpoints from untrusted or malformed input.

Best practices

  • Prefer explicit, typed fields and avoid loosely typed Any for core models.
  • Keep validators minimal and fast; perform heavy work outside model validation.
  • Use strict types when you need to prevent silent coercion (e.g., StrictInt).
  • Use default_factory for mutable defaults to avoid shared state.
  • Emit JSON Schema for public contracts and use model_dump() with by_alias when needed.

Example use cases

  • Define request/response schemas for FastAPI endpoints and rely on automatic validation.
  • Validate incoming webhook payloads, normalize fields, and reject invalid requests with clear errors.
  • Create environment-backed settings via BaseSettings for 12-factor apps.
  • Serialize models to JSON for APIs or persistence using model_dump_json().
  • Generate JSON Schema to drive frontend form validation or API clients.

FAQ

How do I run custom validation across fields?

Use model validators (class methods decorated for the whole model) to inspect and validate multiple fields together.

What if Pydantic coerces types unexpectedly?

Switch to strict types or add explicit validators to enforce exact types and raise errors instead of coercing.