Token导航 LogoToken导航TokenDH.com
研究检索敏感数据github未标认证来源可访问许可证需确认审计未展示

ring%3apre-dev-api-designring 3apre DEV API 设计

Agent Skill

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

总安装

873

周安装

36

GitHub Stars

180

下载量

285
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:ring%3apre-dev-api-design(ring 3apre DEV API 设计)
来源仓库:https://github.com/lerianstudio/ring
仓库路径:skills/ring%3Apre-dev-api-design
安装命令:
npx skills add https://github.com/lerianstudio/ring --skill ring:pre-dev-api-design
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/lerianstudio/ring --skill ring:pre-dev-api-design

简介

ring%3apre-dev-api-design 用于辅助 API 设计、接口文档生成和前后端联调支持。

  • 它可帮助梳理 endpoint、生成 OpenAPI 草稿、检查字段命名和错误码规范。
  • 使用时需结合实际业务语义、鉴权机制和分页规则,避免虚构字段或结构。
  • 建议从现有代码或接口样例中提取事实,确保接口定义准确可靠。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

API/Contract Design - Defining Component Interfaces

Foundational Principle

Component contracts and interfaces must be defined before technology/protocol selection.

Jumping to implementation without contract definition creates:

  • Integration failures discovered during development
  • Inconsistent data structures across components
  • Teams blocked waiting for interface clarity
  • Rework when assumptions about contracts differ

The API Design answers: WHAT data/operations components expose and consume? The API Design never answers: HOW those are implemented (protocols, serialization, specific tech).

Phase 0: API Standards Discovery (MANDATORY)

Before defining contracts, check for organizational naming standards.

See shared-patterns/standards-discovery.md for complete workflow.

Context: API field naming standards Output: docs/pre-dev/{feature-name}/api-standards-ref.md

Use AskUserQuestion tool:

Question: "Do you have a data dictionary or API field naming standards to reference?"

  • Header: "API Standards"
  • multiSelect: false
  • Options:

- "No - Use industry best practices" (description: "Generate contracts using standard naming conventions") - "Yes - URL to document" (description: "Provide a URL to your data dictionary or standards document") - "Yes - File path" (description: "Provide a local file path (.md,.json,.yaml,.csv)")

If "Yes" Selected:

1. Load the document:

Source TypeToolActions
URLWebFetchFetch document content; parse for field definitions, naming rules, validation patterns
File pathReadRead file content; support.md (Markdown tables),.json (structured),.yaml (structured),.csv (tabular)

2. Extract standards:

MUST extract these elements if present:

ElementWhat to ExtractExample
Field naming conventioncamelCase, snake_case, PascalCaseuserId vs user_id
Standard field namesCommon fields used across APIscreatedAt, updatedAt, isActive
Data type formatsHow to represent dates, IDs, amountsISO8601, UUID v4, Decimal(10,2)
Validation patternsRegex, constraints, rulesEmail RFC 5322, phone E.164
Standard error codesOrganizational error namingEMAIL_ALREADY_EXISTS vs DuplicateEmail
Pagination fieldsStandard query/response paginationpage, limit, next_cursor, prev_cursor

3. Save extracted standards:

Output to: docs/pre-dev/{feature-name}/api-standards-ref.md

Format:

# API Standards Reference - {Feature Name}

Source: {URL or file path}
Extracted: {timestamp}

## Field Naming Conventions
- IDs: `{pattern}` (example)
- Timestamps: `{pattern}` (example)
- Booleans: `{pattern}` (example)
- Collections: `{pattern}` (example)

## Standard Fields
| Field | Type | Format | Validation | Example |
|-------|------|--------|------------|---------|
| userId | string | UUID v4 | Required, unique | "550e8400-e29b-41d4-a716-446655440000" |
| email | string | RFC 5322 | Required, unique | "user@example.com" |
| createdAt | string | ISO 8601 | Auto-generated | "2026-01-23T10:30:00Z" |

## Standard Error Codes
| Code | Usage | HTTP Equivalent (for reference) |
|------|-------|--------------------------------|
| EMAIL_ALREADY_EXISTS | Duplicate email registration | 409 Conflict |
| INVALID_INPUT | Validation failure | 400 Bad Request |

## Validation Patterns
| Pattern Type | Rule | Example |
|-------------|------|---------|
| Email | RFC 5322, max 254 chars | "user@example.com" |
| Phone | E.164 format | "+5511987654321" |

## Pagination Standards
| Field | Type | Description |
|-------|------|-------------|
| page | integer | 1-indexed page number (offset-based) |
| limit | integer | Items per page (max 100) |
| next_cursor | string | Base64-encoded cursor for next page (cursor-based) |
| prev_cursor | string | Base64-encoded cursor for previous page (cursor-based) |

4. Apply throughout Gate 4:

  • Use standard field names in operation definitions
  • Reference validation patterns in contract constraints
  • Apply naming conventions consistently
  • Note any justified deviations with rationale

If Dictionary Conflicts with Existing Codebase:

If Phase 0 from Gate 0 (Research) found existing patterns that conflict with the dictionary:

STOP and use AskUserQuestion:

Question: "Dictionary says {dictionary_pattern}, but codebase uses {codebase_pattern}. Which should we follow?"

  • Header: "Standards Conflict"
  • multiSelect: false
  • Options:

- "Follow dictionary" (description: "Use organizational standards, refactor existing code later") - "Follow codebase" (description: "Maintain consistency with existing implementation") - "Hybrid approach" (description: "Let me decide per-field")

If "No" Selected (Industry Best Practices):

Proceed with standard naming conventions:

  • camelCase for field names (JavaScript/TypeScript)
  • snake_case for field names (Python/Ruby/SQL)
  • ISO 8601 for timestamps
  • UUID v4 for identifiers
  • RFC 5322 for emails

Document the choice in api-standards-ref.md with rationale.

Mandatory Workflow

PhaseActivities
0. API Standards DiscoveryCheck for organizational field naming standards (data dictionary); load from URL or file if provided; extract field conventions, types, validation patterns; save to api-standards-ref.md for reference throughout gate
1. Contract AnalysisLoad approved TRD (Gate 3), Feature Map (Gate 2), PRD (Gate 1); identify integration points from TRD component diagram; extract data flows
2. Contract DefinitionPer interface: define operations, specify inputs/outputs, define errors, document events, set constraints (validation), version contracts; apply standards from Phase 0 if available
3. Gate 4 ValidationVerify all checkboxes in validation checklist before proceeding to Data Modeling

Explicit Rules

✅ DO Include

Operation names/descriptions, input parameters (name, type, required/optional, constraints), output structure (fields, types, nullable), error codes/descriptions, event types/payloads, validation rules, idempotency requirements, auth/authz needs (abstract), versioning strategy

❌ NEVER Include

HTTP verbs (GET/POST/PUT), gRPC/GraphQL/WebSocket details, URL paths/routes, serialization formats (JSON/Protobuf), framework code, database queries, infrastructure, specific auth libraries

Abstraction Rules

ElementAbstract (✅)Protocol-Specific (❌)
Operation"CreateUser""POST /api/v1/users"
Data Type"EmailAddress (validated)""string with regex"
Error"UserAlreadyExists""HTTP 409 Conflict"
Auth"Requires authenticated user""JWT Bearer token"
Format"ISO8601 timestamp""time.RFC3339"

Rationalization Table

ExcuseReality
"No need to ask about data dictionary"Organizations have standards. Check first, don't assume. Phase 0 is MANDATORY.
"I'll just use common sense for field names""Common sense" varies. Ask for standards, or explicitly choose best practices.
"Skip Phase 0, user will mention standards if important"User doesn't know when to mention it. YOU must ask proactively.
"REST is obvious, just document endpoints"Protocol choice goes in Dependency Map. Define contracts abstractly.
"We need HTTP codes for errors"Error semantics matter; HTTP codes are protocol. Abstract the errors.
"Teams need to see JSON examples"JSON is serialization. Define structure; format comes later.
"The contract IS the OpenAPI spec"OpenAPI is protocol-specific. Design contracts first, generate specs later.
"gRPC/GraphQL affects the contract"Protocols deliver contracts. Design protocol-agnostic contracts first.
"We already know it's REST"Knowing doesn't mean documenting prematurely. Stay abstract.
"Framework validates inputs"Validation logic is universal. Document rules; implementation comes later.
"This feels redundant with TRD"TRD = components exist. API = how they talk. Different concerns.
"URL structure matters for APIs"URLs are HTTP-specific. Focus on operations and data.
"But API Design means REST API"API = interface. Could be REST, gRPC, events, or in-process. Stay abstract.

Red Flags - STOP

If you catch yourself writing any of these in API Design, STOP:

  • HTTP methods (GET, POST, PUT, DELETE, PATCH)
  • URL paths (/api/v1/users, /users/{id})
  • Protocol names (REST, GraphQL, gRPC, WebSocket)
  • Status codes (200, 404, 500)
  • Serialization formats (JSON, XML, Protobuf)
  • Authentication tokens (JWT, OAuth2 tokens, API keys)
  • Framework code (Express routes, gRPC service definitions)
  • Transport mechanisms (HTTP/2, TCP, UDP)

When you catch yourself: Replace protocol detail with abstract contract. "POST /users" → "CreateUser operation"

Gate 4 Validation Checklist

CategoryRequirements
Contract CompletenessAll component-to-component interactions have contracts; all external integrations covered; all event/message contracts defined; client-facing APIs specified
Operation ClarityEach operation has clear purpose/description; consistent naming convention; idempotency documented; batch operations identified
Data SpecificationAll inputs typed and documented; required vs optional explicit; outputs complete; null/empty cases handled
Error HandlingAll scenarios identified; error codes/types defined; actionable messages; retry/recovery documented
Event ContractsAll events named/described; payloads specified; ordering/delivery semantics documented; versioning defined
Constraints & PoliciesValidation rules explicit; timeouts specified; backward compatibility exists
Technology AgnosticNo protocol specifics; no serialization formats; no framework names; implementable in any protocol

Gate Result: ✅ PASS (all checked) → Data Modeling | ⚠️ CONDITIONAL (remove protocol details) | ❌ FAIL (incomplete)

Contract Template Structure

Output to (path depends on topology.structure):

  • single-repo: docs/pre-dev/{feature-name}/api-design.md
  • monorepo/multi-repo: {backend.path}/docs/pre-dev/{feature-name}/api-design.md
SectionContent
OverviewTRD/Feature Map/PRD references, status, last updated
Versioning StrategyApproach (semantic/date-based), backward compatibility policy, deprecation process
Component ContractsPer component: purpose, integration points (inbound/outbound), operations

Per-Operation Structure

FieldContent
PurposeWhat the operation does
InputsTable: Parameter, Type, Required, Constraints, Description
Validation RulesFormat patterns, business rules
Outputs (Success)Table: Field, Type, Nullable, Description + abstract structure
ErrorsTable: Error Code, Condition, Description, Retry?
IdempotencyBehavior on duplicate calls
AuthorizationRequired permissions (abstract)
Related OperationsEvents triggered, downstream calls

Event Contract Structure

FieldContent
Purpose/When EmittedTrigger conditions
PayloadTable: Field, Type, Nullable, Description
ConsumersServices that consume this event
Delivery SemanticsAt-least-once, at-most-once, exactly-once
Ordering/RetentionOrdering guarantees, retention period

Additional Sections

SectionContent
Cross-Component IntegrationPer integration: purpose, operations used, data flow diagram (abstract), error handling
External System ContractsOperations exposed to us, operations we expose, per-operation details
Custom Type DefinitionsPer type: base type, format, constraints, example
Naming ConventionsOperations (verb+noun), parameters (camelCase), events (past tense), errors (noun+condition)
Backward CompatibilityBreaking vs non-breaking changes, deprecation timeline
Testing ContractsContract testing strategy, example test scenarios
Gate 4 ValidationDate, validator, checklist, approval status

Common Violations

ViolationWrongCorrect
Protocol Details"Endpoint: POST /api/v1/users, Status: 201 Created, 409 Conflict""Operation: CreateUser, Errors: EmailAlreadyExists, InvalidInput"
Implementation CodeJavaScript regex validation code"email must match RFC 5322 format, max 254 chars"
Technology TypesJSON example with "uuid", "Date", "Map<String,Any>"Table with abstract types: Identifier (UUID format), Timestamp (ISO8601), ProfileObject

Confidence Scoring

FactorPointsCriteria
Contract Completeness0-30All ops: 30, Most: 20, Gaps: 10
Interface Clarity0-25Clear/unambiguous: 25, Some interpretation: 15, Vague: 5
Integration Complexity0-25Simple point-to-point: 25, Moderate deps: 15, Complex orchestration: 5
Error Handling0-20All scenarios: 20, Common cases: 12, Minimal: 5

Action: 80+ autonomous generation | 50-79 present options | <50 ask clarifying questions


Document Placement

api-design.md is a backend document - it defines API contracts implemented by backend services.

Structureapi-design.md Location
single-repodocs/pre-dev/{feature}/api-design.md
monorepo{backend.path}/docs/pre-dev/{feature}/api-design.md
multi-repo{backend.path}/docs/pre-dev/{feature}/api-design.md

Why backend path? API contracts are:

  • Implemented by backend engineers
  • Referenced during backend code review
  • Versioned with backend code

Directory creation for multi-module:

# Read topology from research.md frontmatter
backend_path="${topology_modules_backend_path:-"."}"
mkdir -p "${backend_path}/docs/pre-dev/{feature}"

BFF Contract Design (Frontend-only and Fullstack with BFF)

⛔ HARD GATE: If api_pattern: bff (from research.md), this section is MANDATORY.

When This Applies

Check research.md frontmatter:

topology:
  scope: frontend-only | fullstack
  api_pattern: bff  # ← This triggers BFF contract design

Phase 3: BFF Contract Definition

After backend contracts (Phase 2), define BFF-to-Frontend contracts:

StepActivity
1Identify all frontend components that need data
2Map component data needs to backend APIs
3Define BFF aggregation operations
4Specify BFF response contracts (frontend-optimized shapes)
5Document error normalization strategy

BFF Contract Template

Add to api-design.md under ## BFF Contracts section:

## BFF Contracts

### Overview
- **Pattern:** BFF (Backend-for-Frontend)
- **Purpose:** [Aggregation | Transformation | Security | All]
- **Frontend Framework:** [Next.js | React | Vue | etc.]

### BFF Operations

#### Operation: Get{Feature}Data

**Purpose:** Aggregate data for {feature} component

**Frontend Consumer:** `{ComponentName}.tsx`

**Backend APIs Consumed:**
| API | Operation | Purpose |
|-----|-----------|---------|
| User Service | GetUser | User profile data |
| Order Service | ListOrders | Recent orders |

**Input Contract:**
| Parameter | Type | Required | Constraints | Description |
|-----------|------|----------|-------------|-------------|
| userId | Identifier | Yes | Valid UUID | Target user |
| limit | Integer | No | 1-100, default 10 | Max orders |

**Output Contract (Frontend-Optimized):**
| Field | Type | Nullable | Description |
|-------|------|----------|-------------|
| user | UserSummary | No | Simplified user object |
| user.id | Identifier | No | User ID |
| user.displayName | String | No | Formatted name |
| recentOrders | OrderSummary[] | No | Last N orders |
| recentOrders[].id | Identifier | No | Order ID |
| recentOrders[].total | FormattedCurrency | No | Display-ready total |

**Error Normalization:**
| Backend Error | BFF Error Code | Frontend Action |
|---------------|----------------|-----------------|
| User 404 | USER_NOT_FOUND | Redirect to error page |
| Orders 500 | ORDERS_UNAVAILABLE | Show partial data |
| Auth 401 | SESSION_EXPIRED | Trigger re-auth |

Type Transformation Rules

BFF MUST transform backend types to frontend-optimized types:

Backend TypeFrontend TypeTransformation
ISO8601 stringRelativeTime"2 hours ago"
Decimal amountFormattedCurrency"$1,234.56"
Full entitySummary objectSelect display fields
Nested IDsResolved namesJoin data

Frontend-only Specific Requirements

If topology.scope: frontend-only:

The BFF consumes EXISTING backend APIs (documented in PRD Data Sources).

MUST verify:

  1. All PRD Data Sources are covered by BFF operations
  2. All API gaps identified in PRD have corresponding BFF operations
  3. BFF operations match frontend component data needs
### PRD Data Source Coverage

| PRD Data Source | Covered by BFF Operation | Notes |
|-----------------|-------------------------|-------|
| User API | GetDashboardData | User summary included |
| Orders API | GetDashboardData | Recent orders included |
| Reports API | GenerateReport | New BFF operation |

Gate 4 Validation Addition for BFF

CategoryRequirements
BFF CompletenessAll frontend components have data contracts; all backend APIs mapped to BFF operations; error normalization defined; type transformations documented

Rationalization Table for BFF Contracts

ExcuseReality
"BFF is just a proxy"Proxies still transform errors and aggregate. Document contracts.
"Frontend types are implementation"Types define component contracts. Design them here.
"We'll figure out transformations later"Later = bugs. Define transformations upfront.
"Backend contract = frontend contract"Backend serves multiple clients. Frontend needs optimized shapes.
"BFF contracts are obvious from UI"Obvious to you ≠ documented. Write explicit contracts.

After Approval

  1. ✅ Lock contracts - interfaces are now implementation reference
  2. 🎯 Use contracts as input for Data Modeling (ring:pre-dev-data-model)
  3. 🚫 Never add protocol specifics retroactively
  4. 📋 Keep technology-agnostic until Dependency Map

The Bottom Line

If you wrote API contracts with HTTP endpoints or gRPC services, remove them.

Contracts are protocol-agnostic. Period. No REST. No GraphQL. No HTTP codes.

Protocol choices go in Dependency Map. That's a later phase. Wait for it.

Define the contract. Stay abstract. Choose protocol later.


Standards Loading (MANDATORY)

This skill is an API contract design skill and does NOT require WebFetch of language-specific standards.

Purpose: API Design defines WHAT operations and data contracts exist, not HOW they're implemented. Protocol-specific patterns apply during Dependency Map (Gate 6) and implementation.

However, MUST complete Phase 0 (API Standards Discovery) to check for organizational naming standards before designing contracts.


Blocker Criteria - STOP and Report

ConditionActionSeverity
TRD (Gate 3) not validatedSTOP and complete Gate 3 firstCRITICAL
Protocol details in contracts (HTTP verbs, URLs)STOP and abstract to operationsHIGH
Phase 0 not completed (no standards check)STOP and ask user about data dictionaryHIGH
Dictionary conflicts with codebase patternsSTOP and ask user which to followMEDIUM
Operation missing error handlingSTOP and define error contractsMEDIUM
BFF pattern required but contracts missingSTOP and define BFF contractsHIGH

Cannot Be Overridden

These requirements are NON-NEGOTIABLE:

  • MUST NOT include HTTP verbs (GET, POST, PUT, DELETE)
  • MUST NOT include URL paths (/api/v1/users, etc.)
  • MUST NOT include protocol names (REST, GraphQL, gRPC)
  • MUST NOT include HTTP status codes (200, 404, 500)
  • MUST complete Phase 0 (API Standards Discovery) before designing
  • MUST define error contracts for all operations
  • MUST define BFF contracts if api_pattern is bff
  • CANNOT proceed to Gate 5 with protocol-specific content

Severity Calibration

SeverityDefinitionExample
CRITICALCannot proceed with API designTRD not validated, no component boundaries
HIGHContract contains forbidden contentHTTP verbs, URL paths, status codes
MEDIUMContract incomplete but usableMissing error contract for some operations
LOWMinor documentation gapsIdempotency behavior not fully detailed

Pressure Resistance

User SaysYour Response
"REST is obvious, just document endpoints""Cannot include REST specifics. Define operations abstractly. Protocol choice happens in Gate 6."
"We need HTTP codes for errors""Cannot use HTTP codes. Define error semantics abstractly. 'UserNotFound' not '404'."
"Teams need to see JSON examples""Cannot include JSON. JSON is serialization. Define structure abstractly, format later."
"Skip Phase 0, naming is obvious""Cannot skip standards discovery. Organizational standards may exist. I'll check with user first."
"The contract IS the OpenAPI spec""Cannot conflate contract with spec. Design abstract contracts first, generate OpenAPI later."

When This Skill Is Not Needed

  • Small Track workflow (skip to Task Breakdown)
  • Single component system (skip to Data Model)
  • TRD (Gate 3) not validated (complete Gate 3 first)
  • API Design already exists and is validated
  • No component-to-component communication needed
  • Pure frontend feature with no API changes

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.5%
按下载量换算104

Claude

33.01%
按下载量换算94

Cursor

18.75%
按下载量换算53

Gemini CLI

9.65%
按下载量换算28

安全审计

暂无安全审计结果可展示。

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills