pydantic
Validate and serialize data with Pydantic. Use when a user asks to validate API inputs, parse JSON/env config, define data models in Python, serialize objects, or implement data validation with type hints.
What this skill does
# Pydantic
## Overview
Pydantic is a data validation library that uses Python type hints. Define a model class, and Pydantic validates inputs, coerces types, and serializes outputs automatically. Used by FastAPI, LangChain, and most modern Python frameworks.
## Instructions
### Step 1: Basic Models
```python
# schemas.py — Data models with validation
from pydantic import BaseModel, Field, EmailStr, field_validator
from datetime import datetime
class UserCreate(BaseModel):
name: str = Field(min_length=2, max_length=100)
email: EmailStr
age: int = Field(ge=13, le=120)
role: str = Field(default="member", pattern="^(admin|member|viewer)$")
class UserResponse(BaseModel):
id: str
name: str
email: str
role: str
created_at: datetime
model_config = {"from_attributes": True} # works with ORM objects
# Usage
user = UserCreate(name="Alice", email="[email protected]", age=28)
print(user.model_dump()) # {"name": "Alice", "email": "[email protected]", ...}
print(user.model_dump_json()) # JSON string
# Validation error
try:
UserCreate(name="A", email="not-an-email", age=5)
except ValidationError as e:
print(e.errors())
# [{"type": "string_too_short", "loc": ["name"], ...}, ...]
```
### Step 2: Custom Validators
```python
from pydantic import BaseModel, field_validator, model_validator
class ProjectCreate(BaseModel):
name: str
slug: str
start_date: datetime
end_date: datetime | None = None
@field_validator("slug")
@classmethod
def validate_slug(cls, v: str) -> str:
if not v.replace("-", "").isalnum():
raise ValueError("Slug must contain only letters, numbers, and hyphens")
return v.lower()
@model_validator(mode="after")
def validate_dates(self):
if self.end_date and self.end_date <= self.start_date:
raise ValueError("End date must be after start date")
return self
```
### Step 3: Settings from Environment
```python
# config.py — App configuration from env vars
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
redis_url: str = "redis://localhost:6379"
secret_key: str
debug: bool = False
allowed_origins: list[str] = ["http://localhost:3000"]
max_upload_mb: int = 10
model_config = {
"env_file": ".env",
"env_file_encoding": "utf-8",
}
settings = Settings() # auto-reads from .env and environment variables
```
### Step 4: Discriminated Unions
```python
# events.py — Polymorphic event types
from pydantic import BaseModel
from typing import Literal
class TaskCreated(BaseModel):
type: Literal["task.created"] = "task.created"
task_id: str
project_id: str
title: str
class TaskCompleted(BaseModel):
type: Literal["task.completed"] = "task.completed"
task_id: str
completed_by: str
duration_hours: float
class CommentAdded(BaseModel):
type: Literal["comment.added"] = "comment.added"
comment_id: str
task_id: str
body: str
# Discriminated union — Pydantic picks the right type based on "type" field
WebhookEvent = TaskCreated | TaskCompleted | CommentAdded
# Parse any event
event = WebhookEvent.model_validate({"type": "task.completed", "task_id": "123", ...})
# Returns TaskCompleted instance
```
## Guidelines
- Pydantic v2 is 5-50x faster than v1 — rewritten in Rust (pydantic-core).
- Use `Field(...)` for constraints: `min_length`, `max_length`, `ge`, `le`, `pattern`.
- `from_attributes = True` enables direct serialization of ORM objects (SQLAlchemy, Django).
- Use `pydantic-settings` for type-safe configuration from environment variables.
- Discriminated unions handle polymorphic data — Pydantic picks the right model based on a field value.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.