pydantic

Data validation and settings management using Python type annotations with Pydantic v2

242 stars

Best use case

pydantic is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. Data validation and settings management using Python type annotations with Pydantic v2

Data validation and settings management using Python type annotations with Pydantic v2

Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.

Practical example

Example input

Use the "pydantic" skill to help with this workflow task. Context: Data validation and settings management using Python type annotations with Pydantic v2

Example output

A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.

When to use this skill

  • Use this skill when you want a reusable workflow rather than writing the same prompt again and again.

When not to use this skill

  • Do not use this when you only need a one-off answer and do not need a reusable workflow.
  • Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/pydantic/SKILL.md --create-dirs "https://raw.githubusercontent.com/aiskillstore/marketplace/main/skills/bossjones/pydantic/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/pydantic/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How pydantic Compares

Feature / AgentpydanticStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Data validation and settings management using Python type annotations with Pydantic v2

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Pydantic v2 Framework Skill

Pydantic is a data validation library that uses Python type annotations to define data schemas, offering fast and extensible validation with automatic type coercion.

## Quick Start

### Basic Model Definition

```python
from pydantic import BaseModel
from datetime import datetime
from typing import Optional

class User(BaseModel):
    id: int
    name: str
    email: str
    signup_ts: Optional[datetime] = None
    is_active: bool = True

# Automatic type coercion
user = User(
    id='123',  # String → int
    name='John Doe',
    email='john@example.com',
    signup_ts='2017-06-01 12:22'  # String → datetime
)
```

### Validation from Data Sources

```python
# From dict
user = User.model_validate({'id': 1, 'name': 'Alice', 'email': 'alice@test.com'})

# From JSON
user = User.model_validate_json('{"id": 1, "name": "Alice", "email": "alice@test.com"}')

# Serialization
print(user.model_dump())  # Python dict
print(user.model_dump_json())  # JSON string
```

## Common Patterns

### Field Configuration

```python
from pydantic import BaseModel, Field, EmailStr, HttpUrl
from typing import Annotated

class Product(BaseModel):
    product_id: int = Field(alias='id', ge=1, description='Unique product identifier')
    name: str = Field(min_length=1, max_length=200)
    price: float = Field(gt=0, le=1000000)
    email: EmailStr
    website: HttpUrl
    tags: list[str] = Field(default_factory=list, max_length=10)
    internal_code: str = Field(exclude=True, default='N/A')

class User(BaseModel):
    username: Annotated[str, Field(min_length=3, pattern=r'^[a-zA-Z0-9_]+$')]
    age: int = Field(ge=0, le=150)
```

### Model Configuration

```python
from pydantic import BaseModel, ConfigDict

class StrictModel(BaseModel):
    model_config = ConfigDict(
        strict=True,              # No type coercion
        frozen=True,              # Immutable instances
        validate_assignment=True, # Validate on attribute assignment
        extra='forbid',           # Reject extra fields
        str_strip_whitespace=True,
        populate_by_name=True,    # Accept both alias and field name
        use_enum_values=True,     # Serialize enums as values
    )

    id: int
    name: str
```

### Custom Validation

```python
from pydantic import BaseModel, model_validator, field_validator, ValidationError
from typing import Any

class DateRange(BaseModel):
    start_date: str
    end_date: str

    @field_validator('start_date', 'end_date')
    @classmethod
    def validate_date_format(cls, v: str) -> str:
        # Custom validation logic
        if not v:
            raise ValueError('Date cannot be empty')
        return v

    @model_validator(mode='after')
    def check_dates_order(self) -> 'DateRange':
        # Cross-field validation
        if self.start_date > self.end_date:
            raise ValueError('start_date must be before end_date')
        return self

# Using the model
try:
    date_range = DateRange(start_date='2024-01-01', end_date='2024-01-31')
except ValidationError as e:
    for error in e.errors():
        print(f"{error['loc']}: {error['msg']}")
```

### Serialization Control

```python
from pydantic import BaseModel, Field, SecretStr
from datetime import datetime

class User(BaseModel):
    id: int
    username: str
    password: SecretStr
    created_at: datetime
    internal_data: dict = Field(exclude=True, default_factory=dict)

# Serialization options
user = User(
    id=1,
    username='john',
    password='secret',
    created_at=datetime.now()
)

# Basic serialization
print(user.model_dump())  # Python dict
print(user.model_dump_json())  # JSON string

# Excluding fields
print(user.model_dump(exclude={'password'}))
print(user.model_dump(exclude={'username', 'created_at'}))

# Include only specific fields
print(user.model_dump(include={'id', 'username'}))

# JSON-compatible serialization
print(user.model_dump(mode='json'))  # datetime → string
print(user.model_dump(by_alias=True))  # Use field aliases
```

### Custom Serialization

```python
from typing import Annotated, Any
from pydantic import BaseModel, field_serializer, PlainSerializer

class Model(BaseModel):
    number: int
    created_at: datetime

    @field_serializer('number')
    def serialize_number(self, value: int) -> str:
        return f"{value:,}"  # Format with commas

    # Using Annotated with PlainSerializer
    custom_field: Annotated[
        float,
        PlainSerializer(lambda x: round(x, 2), return_type=float)
    ]
```

### Nested Models and Relationships

```python
from pydantic import BaseModel
from typing import Optional, List

class Address(BaseModel):
    street: str
    city: str
    country: str = 'USA'
    zip_code: str

class User(BaseModel):
    id: int
    name: str
    addresses: List[Address]
    primary_address: Optional[Address] = None

# Usage
user = User(
    id=1,
    name='John Doe',
    addresses=[
        {'street': '123 Main St', 'city': 'New York', 'zip_code': '10001'},
        {'street': '456 Oak Ave', 'city': 'Boston', 'zip_code': '02101'}
    ],
    primary_address={'street': '123 Main St', 'city': 'New York', 'zip_code': '10001'}
)
```

### Enum Integration

```python
from enum import Enum, IntEnum
from pydantic import BaseModel

class Status(str, Enum):
    PENDING = 'pending'
    ACTIVE = 'active'
    COMPLETED = 'completed'

class Priority(IntEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

class Task(BaseModel):
    title: str
    status: Status = Status.PENDING
    priority: Priority = Priority.MEDIUM

    model_config = ConfigDict(use_enum_values=True)

# Can use enum values or names
task1 = Task(title='Task 1', status='active', priority=3)
task2 = Task(title='Task 2', status=Status.ACTIVE, priority=Priority.HIGH)
```

### TypeAdapter for Standalone Validation

```python
from pydantic import TypeAdapter
from typing import List, Optional

# Validate individual types without full models
int_adapter = TypeAdapter(int)
print(int_adapter.validate_python('123'))  # 123

list_adapter = TypeAdapter(List[int])
print(list_adapter.validate_python(['1', '2', '3']))  # [1, 2, 3]

# Generate JSON schemas
print(int_adapter.json_schema())
print(list_adapter.json_schema())
```

### Data Validation Patterns

```python
from pydantic import BaseModel, ValidationError
from typing import Union

class EmailValidator(BaseModel):
    email: str

    @field_validator('email')
    @classmethod
    def validate_email(cls, v: str) -> str:
        if '@' not in v:
            raise ValueError('Invalid email format')
        return v.lower()

# Validation error handling
try:
    user = User(id='invalid', name='', email='test')
except ValidationError as e:
    print(f"Errors: {e.error_count()}")
    for error in e.errors():
        print(f"  {error['loc']}: {error['msg']} ({error['type']})")
```

## Requirements

- Python 3.8+
- Pydantic v2.x: `uv add pydantic`
- Optional dependencies for enhanced types:
  - `uv add pydantic[email]` for EmailStr
  - `uv add pydantic[url]` for HttpUrl
  - `uv add pydantic[typing-extensions]` for extended type support

## Best Practices

1. **Use specific types**: Prefer `conint(gt=0)` over `int` for positive numbers
2. **Configure models**: Use `ConfigDict` to set global model behavior
3. **Handle validation errors**: Always wrap model creation in try/catch blocks
4. **Use field validators**: Implement custom validation logic with `@field_validator`
5. **Control serialization**: Use `model_dump()` parameters to control output format
6. **Leverage type coercion**: Pydantic automatically converts compatible types
7. **Use nested models**: Break complex data into smaller, reusable models

Related Skills

pydantic-models-py

242
from aiskillstore/marketplace

Create Pydantic models following the multi-model pattern with Base, Create, Update, Response, and InDB variants. Use when defining API request/response schemas, database models, or data validation in Python applications using Pydantic v2.

pydanticai-docs

242
from aiskillstore/marketplace

Use this skill for requests related to Pydantic AI framework - building agents, tools, dependencies, structured outputs, and model integrations.

py-pydantic-patterns

242
from aiskillstore/marketplace

Pydantic v2 patterns for validation and serialization. Use when creating schemas, validating data, or working with request/response models.

azure-quotas

242
from aiskillstore/marketplace

Check/manage Azure quotas and usage across providers. For deployment planning, capacity validation, region selection. WHEN: "check quotas", "service limits", "current usage", "request quota increase", "quota exceeded", "validate capacity", "regional availability", "provisioning limits", "vCPU limit", "how many vCPUs available in my subscription".

DevOps & Infrastructure

raindrop-io

242
from aiskillstore/marketplace

Manage Raindrop.io bookmarks with AI assistance. Save and organize bookmarks, search your collection, manage reading lists, and organize research materials. Use when working with bookmarks, web research, reading lists, or when user mentions Raindrop.io.

Data & Research

zlibrary-to-notebooklm

242
from aiskillstore/marketplace

自动从 Z-Library 下载书籍并上传到 Google NotebookLM。支持 PDF/EPUB 格式,自动转换,一键创建知识库。

discover-skills

242
from aiskillstore/marketplace

当你发现当前可用的技能都不够合适(或用户明确要求你寻找技能)时使用。本技能会基于任务目标和约束,给出一份精简的候选技能清单,帮助你选出最适配当前任务的技能。

web-performance-seo

242
from aiskillstore/marketplace

Fix PageSpeed Insights/Lighthouse accessibility "!" errors caused by contrast audit failures (CSS filters, OKLCH/OKLAB, low opacity, gradient text, image backgrounds). Use for accessibility-driven SEO/performance debugging and remediation.

project-to-obsidian

242
from aiskillstore/marketplace

将代码项目转换为 Obsidian 知识库。当用户提到 obsidian、项目文档、知识库、分析项目、转换项目 时激活。 【激活后必须执行】: 1. 先完整阅读本 SKILL.md 文件 2. 理解 AI 写入规则(默认到 00_Inbox/AI/、追加式、统一 Schema) 3. 执行 STEP 0: 使用 AskUserQuestion 询问用户确认 4. 用户确认后才开始 STEP 1 项目扫描 5. 严格按 STEP 0 → 1 → 2 → 3 → 4 顺序执行 【禁止行为】: - 禁止不读 SKILL.md 就开始分析项目 - 禁止跳过 STEP 0 用户确认 - 禁止直接在 30_Resources 创建(先到 00_Inbox/AI/) - 禁止自作主张决定输出位置

obsidian-helper

242
from aiskillstore/marketplace

Obsidian 智能笔记助手。当用户提到 obsidian、日记、笔记、知识库、capture、review 时激活。 【激活后必须执行】: 1. 先完整阅读本 SKILL.md 文件 2. 理解 AI 写入三条硬规矩(00_Inbox/AI/、追加式、白名单字段) 3. 按 STEP 0 → STEP 1 → ... 顺序执行 4. 不要跳过任何步骤,不要自作主张 【禁止行为】: - 禁止不读 SKILL.md 就开始工作 - 禁止跳过用户确认步骤 - 禁止在非 00_Inbox/AI/ 位置创建新笔记(除非用户明确指定)

internationalizing-websites

242
from aiskillstore/marketplace

Adds multi-language support to Next.js websites with proper SEO configuration including hreflang tags, localized sitemaps, and language-specific content. Use when adding new languages, setting up i18n, optimizing for international SEO, or when user mentions localization, translation, multi-language, or specific languages like Japanese, Korean, Chinese.

google-official-seo-guide

242
from aiskillstore/marketplace

Official Google SEO guide covering search optimization, best practices, Search Console, crawling, indexing, and improving website search visibility based on official Google documentation