/py-pit:pydantic-schemasfrom py-pit
Provides opinionated Pydantic v2 schema patterns for Python API projects: request, response, query, command, batch, and pagination models. Prevents schema drift in new FastAPI or API backends.
Ships in py-pit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Opinionated guidance for designing API request/response schemas using Pydantic v2 in new Python backend projects.
This skill is optimized for 0→1 API projects where schema
conventions have not yet been established.
Its purpose is to prevent schema drift, eliminate repeated
architectural decisions, and enforce a consistent API boundary between
domain models and external representations.
This skill does not teach Pydantic basics.
It constrains schema architecture so the model consistently generates
predictable request, response, query, and command structures.
Apply this skill when the user:
Trigger phrases (user language):
"add a schema for orders", "how should I structure my Pydantic models?", "I need a request body for creating a user", "what's the right way to do partial updates?", "how do I return paginated results?", "should I use the same model for create and update?", "how do I model a cancel order action?", "I need a search endpoint with filters"
Do not apply this skill when:
When this skill is active, the model's job is to produce or extend schema code that follows this taxonomy without deviation, ask no unnecessary questions, and leave the caller with working, importable schema classes.
These rules prevent the most common schema mistakes in early-stage API projects.
MUST NOT:
Optional[T] to mean both "field may be omitted" and "field
may be null" without being deliberate about which behavior is
intended.If the repository already has established schema conventions, follow those conventions unless the user asks to refactor toward this structure.
Step 1 — Inspect existing schemas
Before generating anything, check whether the repo already has a
schemas/ directory or existing Pydantic models. If it does:
Step 2 — Generate or extend schemas
schemas/base.py first, then the
resource module.model_dump(exclude_unset=True) usage in the service layer
whenever an Update schema is generated.Step 3 — Verify and present
For new projects schemas SHOULD follow this layout:
schemas/
base.py
user.py
order.py
pagination.py
common.py
base.py defines shared base schema types:
Resource schemas should live in their own module (e.g. schemas/user.py).
Each API should use explicit schema roles. Do not collapse unrelated endpoint types into CRUD-only naming.
| Schema Role | Purpose |
|---|---|
| Create | Request body for resource creation |
| Update | Partial update payload |
| Read | Response serialization for a resource |
| Filter / Query | Search, list, and filtering inputs |
| CommandRequest | Action-oriented request body |
| CommandResponse | Action-oriented response body |
| BatchRequest | Batch operation request body |
| Page | Paginated response envelope |
| Summary / Report | Aggregate or computed response shape |
| Internal (optional) | Service-layer DTO |
Rules:
All schemas MUST inherit from a shared base class.
Example:
from pydantic import BaseModel, ConfigDict
class APIModel(BaseModel):
model_config = ConfigDict(
extra="forbid",
str_strip_whitespace=True,
validate_assignment=True,
use_enum_values=True,
populate_by_name=True,
)
These defaults enforce:
The remaining base classes are thin role markers. They exist to enforce naming discipline, not to add behavior (except where noted):
class CreateModel(APIModel):
"""Request body for resource creation."""
class UpdateModel(APIModel):
"""Partial update payload. Use model_dump(exclude_unset=True) in the service layer."""
class QueryModel(APIModel):
"""Search, list, and filtering inputs. All fields should be optional."""
model_config = APIModel.model_config.copy()
model_config["extra"] = "ignore"
class CommandModel(APIModel):
"""Action-oriented request body for non-CRUD endpoints."""
class BatchModel(APIModel):
"""Batch operation request body."""
QueryModel uses extra="ignore" because query parameters may include
pagination or framework-injected fields that should not cause validation
errors.
Response models MUST support serialization from ORM objects.
class ReadModel(APIModel):
model_config = APIModel.model_config.copy()
model_config["from_attributes"] = True
ORM objects SHOULD be converted using:
UserRead.model_validate(user)
Avoid:
Create models represent new resource creation.
Rules:
Example:
class UserCreate(CreateModel):
email: EmailStr
name: str
Update models represent partial updates.
Fields SHOULD be optional when omission means "leave unchanged":
class UserUpdate(UpdateModel):
name: str | None = None
email: EmailStr | None = None
Updates MUST apply only provided fields:
updates = update.model_dump(exclude_unset=True)
for field, value in updates.items():
setattr(user, field, value)
Full model dumps MUST NOT be used for partial updates.
Be explicit about the difference between:
null: clear the value, if the API allows itDo not blur these two behaviors accidentally.
Search and listing endpoints SHOULD use explicit query/filter schemas instead of ad hoc parameter groupings.
Example:
class UserFilter(QueryModel):
email: str | None = None
active: bool | None = None
created_after: datetime | None = None
Use filter/query schemas for:
Do not invent different filter naming conventions per endpoint.
Non-CRUD endpoints need explicit schema types too - do not inline these as untyped dicts.
Non-CRUD actions (activate user, cancel order, refund payment, generate report) use explicit command request/response schemas.
class RefundPaymentRequest(CommandModel):
reason: str
notify_customer: bool = True
class RefundPaymentResponse(APIModel):
payment_id: int
status: str
refunded_at: datetime
Naming pattern - pick one and use it consistently:
{Action}{Resource}Request, or{Resource}{Action}RequestBatch operations use explicit batch request models.
class BulkDisableUsersRequest(BatchModel):
user_ids: list[int]
Do not pass bare lists as request bodies when the payload has semantic meaning.
Computed endpoints (analytics, reports, summaries, stats) MUST use explicit response schemas.
class RevenueSummary(APIModel):
total_revenue: Decimal
total_orders: int
average_order_value: Decimal
Do not return raw dictionaries for stable API responses.
APIs SHOULD use a consistent pagination structure.
from typing import Generic, TypeVar
from pydantic import BaseModel
T = TypeVar("T")
class Page(BaseModel, Generic[T]):
items: list[T]
total: int
limit: int
offset: int
Endpoints SHOULD return:
Page[UserRead]
Resource-specific pagination types MUST NOT be created unless necessary.
Normalization and validation SHOULD live in Pydantic validators, not routers or services.
Example:
from pydantic import field_validator
class UserCreate(CreateModel):
email: EmailStr
@field_validator("email")
@classmethod
def normalize_email(cls, value: str) -> str:
return value.lower()
Routers and services SHOULD assume validated input.
Schemas MUST follow explicit naming patterns.
Recommended patterns:
{Resource}Create{Resource}Update{Resource}Read{Resource}Filter{Action}{Resource}Request{Action}{Resource}Response{Resource}SummaryAvoid ambiguous names such as:
Schema names should clearly communicate their role.
Before responding, verify:
APIModel or ReadModelmodel_dump(exclude_unset=True)Page[T], not a resource-specific typeApplying this skill ensures:
What SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (robhowley/py-pit-skills) — no native marketplace selected
npx claudepluginhub p/robhowley-py-pit16 skills in this plugin
/alembic-migrationsProduction-safe Alembic migration workflows for SQLAlchemy 2.x projects. Use this skill when adding Alembic, generating migrations, reviewing autogenerate diffs, fixing broken migrations, or establishing a safe schema evolution workflow in a Python backend./background-jobs-boundariesGuardrails for background work in FastAPI and Python services. Prevent misuse of in-process background execution (e.g. FastAPI BackgroundTasks)./click-cliDesign, generate, and improve Python CLIs using the Click library. Focus on idiomatic architecture, command groups, modular layouts, CLI UX conventions, and avoiding common Click anti-patterns./click-cli-linterAudit and improve existing Python Click CLIs by identifying architecture problems, anti-patterns, and CLI UX issues, then proposing minimal, high-value fixes./code-qualityOpinionated code health stack for Python repos using Ruff, pre-commit, and Markdown linting. Prefers consolidation over redundant tooling, preserves working repos unless migration is requested, and provides a simple adoption path for both new and existing projects./dockerize-serviceGenerate a local-development Docker Compose setup for an existing Python project. Produces a multi-stage Dockerfile, Compose file, env config, and dockerignore based on detected project signals.Other plugins' skills for the same job