技能 编程开发 使用Pydantic模型定义API契约

使用Pydantic模型定义API契约

v20260423
pydantic-models-py
该技能指导开发者如何使用Pydantic库遵循多模型模式(Multi-Model Pattern)来构建清晰、健壮的API数据契约。它为资源创建、更新、响应和数据库操作分别定义了模型,确保了Python后端的数据类型安全性和数据校验的准确性。
获取技能
147 次下载
概览

Pydantic Models

Create Pydantic models following the multi-model pattern for clean API contracts.

Quick Start

Copy the template from assets/template.py and replace placeholders:

  • {{ResourceName}} → PascalCase name (e.g., Project)
  • {{resource_name}} → snake_case name (e.g., project)

Multi-Model Pattern

Model Purpose
Base Common fields shared across models
Create Request body for creation (required fields)
Update Request body for updates (all optional)
Response API response with all fields
InDB Database document with doc_type

camelCase Aliases

class MyModel(BaseModel):
    workspace_id: str = Field(..., alias="workspaceId")
    created_at: datetime = Field(..., alias="createdAt")
    
    class Config:
        populate_by_name = True  # Accept both snake_case and camelCase

Optional Update Fields

class MyUpdate(BaseModel):
    """All fields optional for PATCH requests."""
    name: Optional[str] = Field(None, min_length=1)
    description: Optional[str] = None

Database Document

class MyInDB(MyResponse):
    """Adds doc_type for Cosmos DB queries."""
    doc_type: str = "my_resource"

Integration Steps

  1. Create models in src/backend/app/models/
  2. Export from src/backend/app/models/__init__.py
  3. Add corresponding TypeScript types

When to Use

This skill is applicable to execute the workflow or actions described in the overview.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
信息
Category 编程开发
Name pydantic-models-py
版本 v20260423
大小 1.97KB
更新时间 2026-04-24
语言