Token导航 LogoToken导航

Agent Skill · 待分类

api-design(API 设计)

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

api-design 是待分类类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在待分类类的 11,209 个 Skill 里排第 7,849。

总安装 339周安装 14GitHub Stars 643下载 111核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/citypaul/.dotfiles --skill api-design

这个 Skill 是做什么的

这个 Skill 的分类还没最终确定,用法以来源仓库的说明为准。

api-design 辅助梳理接口结构与文档,支持 OpenAPI 草案生成。适合在 Codex、Claude、Cursor、Gemini CLI 中协调前后端联调时使用。需基于真实业务语义定义字段,避免虚构参数或错误状态码。当前无详细技能说明,请查阅 GitHub 仓库获取更多信息。

api-design 属于待分类类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/api-design

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/citypaul/.dotfiles --skill api-design;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

api-design 怎么安装?

在终端执行 npx skills add https://github.com/citypaul/.dotfiles --skill api-design。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

api-design 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

api-design 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

api-design 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

api-design 用的人多吗?

公开数据是累计安装 339 次,近一周安装 14 次,下载 111 次,GitHub 643 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

api-design 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理待分类类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

待分类类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
infsh-cli

infsh CLI · Codex、Claude

4,374,576382权限未标注未明确未收录
ai-video-generation

AI 视频生成 · Codex、Claude

4,313,376382调用外部服务未明确有提醒
lark-openapi-explorer

云雀 OpenAPI 浏览器 · Codex、Claude

2,064,1209,011需要联网未明确有提醒
lark-workflow-standup-report

Lark 工作流程站立报告 · Codex、Claude

2,041,6328,978需要联网未明确通过
use-my-browser

使用我的浏览器 · Codex、Claude

1,848,49140操作浏览器未明确未通过
api-design

API 设计 · 本页

339643需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

name
api-design
description
Stable API and interface design patterns. Use when designing REST endpoints, module boundaries, component prop interfaces, or any public contract between systems. Covers contract-first development, error semantics (RFC 9457), REST conventions, pagination, idempotency, rate limiting, and backward compatibility. For TypeScript type patterns (branded types, discriminated unions, schemas), see typescript-strict. For validation at trust boundaries, see typescript-strict.

API and Interface Design

For TypeScript type patterns (branded types, discriminated unions, schema-first), see the typescript-strict skill. For immutability patterns, see the functional skill. For testing API behavior, see the testing skill. For versioning strategies and deprecation patterns, see resources/api-evolution.md. For security at the API boundary, see resources/api-security.md. For HTTP protocol fundamentals (caching, browser security, status codes, headers), see resources/http-fundamentals.md. For JWT and OAuth 2.0 security deep-dive, see resources/auth-security.md.

When to Use

  • Designing new API endpoints
  • Defining module boundaries or contracts between teams
  • Creating component prop interfaces
  • Changing existing public interfaces
  • Establishing database schema that informs API shape

Core Principles

Hyrum's Law

With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract.

Every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it.

  • Be intentional about what you expose. Every observable behavior is a potential commitment.
  • Don't leak implementation details. If users can observe it, they will depend on it.
  • Plan for deprecation at design time. Removing things users depend on always costs more than expected.
  • Tests are not enough. Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.

The One-Version Rule

Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork.

Contract First

Define the interface before implementing it. The contract is the spec — implementation follows.

type TaskAPI = {
  readonly createTask: (input: CreateTaskInput) => Promise<Task>;
  readonly listTasks: (params: ListTasksParams) => Promise<PaginatedResult<Task>>;
  readonly getTask: (id: TaskId) => Promise<Task>;
  readonly updateTask: (id: TaskId, input: UpdateTaskInput) => Promise<Task>;
  readonly deleteTask: (id: TaskId) => Promise<void>;
};

This aligns with TDD: define the contract (what you want), write tests against it, then implement.

Prefer Addition Over Modification

Extend interfaces without breaking existing consumers:

type CreateTaskInput = {
  readonly title: string;
  readonly description?: string;
  readonly priority?: 'low' | 'medium' | 'high';  // Added later, optional
  readonly labels?: ReadonlyArray<string>;           // Added later, optional
};

What breaks backward compatibility:

  • Removing fields
  • Changing field types
  • Making optional fields required
  • Changing enum values

What preserves backward compatibility:

  • Adding new optional fields
  • Adding new enum values (if consumers handle unknown values)
  • Adding new endpoints

Consistent Error Semantics

Pick one error strategy and use it everywhere. Don't mix patterns where some endpoints throw, others return null, and others return { error }.

Choosing an Error Format

The non-negotiable: Pick one error shape and use it for every endpoint. Consistency matters more than which format you choose.

For public APIs with external consumers, use RFC 9457 (Problem Details). It's the industry standard, machine-readable, and what third-party developers expect. Use application/problem+json as the Content-Type.

For internal APIs with a single frontend, a simpler consistent shape is a valid choice. The minimum viable error response needs: a machine-readable error code, an optional human-readable message, and the correct HTTP status code. This is less ceremony than RFC 9457 while still being consistent and actionable.

// Simpler shape — sufficient for internal APIs
type ApiError = {
  readonly error: string;                          // Machine-readable code (UPPER_SNAKE_CASE)
  readonly message?: string;                       // Human-readable description
  readonly fieldErrors?: Record<string, string>;   // For validation errors
};

If you start with a simpler format, design it so it can evolve toward RFC 9457 later (e.g., error maps to title, message maps to detail). Don't paint yourself into a corner.

RFC 9457 (Problem Details for HTTP APIs)

The standard format for machine-readable API errors for public APIs. Use application/problem+json as the Content-Type.

Standard members:

type ProblemDetail = {
  readonly type: string;       // URI identifying the error type (defaults to "about:blank")
  readonly title: string;      // Human-readable summary — MUST NOT change between occurrences
  readonly status: number;     // HTTP status code — MUST match the actual HTTP response status
  readonly detail: string;     // Explanation specific to this occurrence — help the client fix it
  readonly instance?: string;  // URI identifying this specific occurrence
};

When type is absent or "about:blank", the problem has no additional semantics beyond the HTTP status code. Use title matching the standard HTTP phrase (e.g., "Not Found" for 404).

When type is a resolvable URI (http/https), it SHOULD point to human-readable documentation explaining how to resolve the problem.

Example — single error:

{
  "type": "https://api.example.com/problems/insufficient-funds",
  "title": "Insufficient Funds",
  "status": 422,
  "detail": "Your account balance of $5.00 is insufficient for a $10.00 transfer.",
  "instance": "/transfers/abc123",
  "balance": 30
}

Extension members (like balance above) are allowed — clients MUST ignore extensions they don't recognize, which enables forward-compatible evolution of error responses.

Example — validation errors (multiple problems of the same type use an extension array with JSON Pointer):

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Your request is not valid.",
  "status": 422,
  "detail": "2 validation errors",
  "errors": [
    { "detail": "must be a positive integer", "pointer": "#/age" },
    { "detail": "must be 'green', 'red' or 'blue'", "pointer": "#/profile/color" }
  ]
}

For multiple problems of different types, return the most relevant or urgent one — don't create batch problem types (they don't map well into HTTP semantics).

When NOT to use Problem Details:

  • Generic problems expressed well by plain status codes (e.g., a simple 404 doesn't always need a body)
  • When your application already defines a more appropriate error format
  • As a debugging tool for internal implementation

Errors should be actionable: the consumer should know what went wrong, why, and what to do about it.

Security (RFC 9457 §5): Error responses must help clients correct issues, not serve as debugging tools. Every field in a problem detail is a potential information leak:

  • Never expose stack traces, internal paths, or server implementation details — these are attack vectors
  • Vet new problem types for information that could compromise the system or user privacy
  • Avoid linking to internal occurrence data through the HTTP interface (e.g., don't link to internal log entries)
  • The status field duplicates the HTTP status code — if they disagree, clients may behave unpredictably; keep them in sync

HTTP Status Code Mapping

StatusMeaningWhen to use
400Bad RequestClient sent malformed data
401UnauthorizedNot authenticated
403ForbiddenAuthenticated but not authorized
404Not FoundResource doesn't exist
409ConflictDuplicate, version mismatch
422Unprocessable EntityValidation failed (semantically invalid)
429Too Many RequestsRate limit exceeded (include Retry-After header)
500Internal Server ErrorServer error (never expose internal details)

Validation at API Boundaries

Validate where external input enters your system. Trust internal code after validation. See the typescript-strict skill for schema-first patterns.

app.post('/api/tasks', async (req, res) => {
  const result = CreateTaskSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(422).json({
      type: 'https://api.example.com/problems/validation-error',
      title: 'Validation Error',
      status: 422,
      detail: 'Invalid task data',
      errors: result.error.flatten(),
    });
  }

  const task = await taskService.create(result.data);
  return res.status(201).json(task);
});

Third-party API responses are untrusted data — always validate their shape and content before use.

Idempotency

Network failures happen. Clients retry. Without idempotency, retries create duplicate charges, duplicate orders, duplicate records.

HTTP Method Idempotency

MethodSafeIdempotentNotes
GETYesYesNo side effects
PUTNoYesSame request = same result
DELETENoYesDeleting twice = same outcome
POSTNoNoNeeds explicit idempotency handling
PATCHNoNot guaranteedDepends on implementation

Idempotency Keys for POST

For non-idempotent operations (especially those involving money, orders, or state changes), use client-provided idempotency keys:

app.post('/api/payments', async (req, res) => {
  const idempotencyKey = req.headers['idempotency-key'];
  if (!idempotencyKey) {
    return res.status(400).json({
      type: 'https://api.example.com/problems/missing-idempotency-key',
      title: 'Missing Idempotency Key',
      status: 400,
      detail: 'POST /api/payments requires an Idempotency-Key header',
    });
  }

  const cached = await idempotencyStore.get(idempotencyKey);
  if (cached) {
    return res.status(cached.status).json(cached.body);
  }

  const payment = await paymentService.create(result.data);
  await idempotencyStore.set(idempotencyKey, {
    status: 201,
    body: payment,
  });

  return res.status(201).json(payment);
});

Design principles:

  • Keys should be scoped to the API key / authenticated user
  • Keys should expire (24 hours is typical)
  • If parameters differ on retry with the same key, return an error
  • Design for "at-least-once" delivery — assume every request might be sent multiple times

Making DELETE Idempotent

DELETE should succeed even if the resource is already gone:

app.delete('/api/tasks/:id', async (req, res) => {
  const deleted = await taskService.delete(req.params.id);
  // Return 204 whether the resource existed or was already deleted
  return res.status(204).send();
});

Rate Limiting

Communicate limits clearly via headers on every response — not just 429s.

Standard Headers

RateLimit-Limit: 1000          # Max requests per window
RateLimit-Remaining: 742       # Requests left in current window
RateLimit-Reset: 60            # Seconds until window resets

On 429 responses, always include Retry-After:

HTTP/1.1 429 Too Many Requests
Retry-After: 30
RateLimit-Limit: 1000
RateLimit-Remaining: 0
RateLimit-Reset: 30
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/rate-limit-exceeded",
  "title": "Rate Limit Exceeded",
  "status": 429,
  "detail": "You have exceeded 1000 requests per hour. Retry after 30 seconds."
}

Design Considerations

  • Different limits for different operations — reads are cheaper than writes
  • Communicate limits in documentation — don't make consumers discover them by hitting 429s
  • Recommend exponential backoff with jitter in your docs — naive retry loops cause thundering herds

HTTP Caching

Assign explicit freshness lifetimes on responses. Don't rely on heuristic freshness.

DirectiveMeaningCommon misconception
Cache-Control: max-age=NFresh for N seconds. Preferred over Expires.--
Cache-Control: no-cacheMay be stored, but must revalidate before every use.Often confused with "don't cache"
Cache-Control: no-storeMust NOT be stored at all. Use this to prevent caching.--
Cache-Control: must-revalidateOnce stale, must revalidate. Cannot serve stale when disconnected.--

Practical rules:

  • Even short freshness (e.g., max-age=5) enables reuse across multiple clients
  • Assign ETags for efficient revalidation without re-transferring the body
  • If a request header changes the response, use Vary on ALL responses from that resource (including the default)
  • Use no-store for responses containing sensitive data (not no-cache)

See resources/http-fundamentals.md for full caching guidance including content negotiation, header design, and protocol version independence.

REST Conventions

Resource Naming

PatternConventionExample
EndpointsPlural nouns, no verbsGET /api/tasks, POST /api/tasks
Query paramscamelCase?sortBy=createdAt&pageSize=20
Response fieldscamelCase{ createdAt, updatedAt, taskId }
Boolean fieldsis/has/can prefixisComplete, hasAttachments
Enum valuesUPPER_SNAKE"IN_PROGRESS", "COMPLETED"
HeadersNo X- prefix (RFC 6648/BCP 178)Example-Request-Id

Resource Design

GET    /api/tasks              → List tasks (with query params for filtering)
POST   /api/tasks              → Create a task
GET    /api/tasks/:id          → Get a single task
PATCH  /api/tasks/:id          → Update a task (partial)
DELETE /api/tasks/:id          → Delete a task

GET    /api/tasks/:id/comments → List comments for a task (sub-resource)
POST   /api/tasks/:id/comments → Add a comment to a task

Use PATCH for partial updates (only provided fields change). Use PUT only when the client sends the complete object.

Pagination

Always paginate list endpoints:

// Request
// GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc

// Response shape
type PaginatedResult<T> = {
  readonly data: ReadonlyArray<T>;
  readonly pagination: {
    readonly page: number;
    readonly pageSize: number;
    readonly totalItems: number;
    readonly totalPages: number;
  };
};

Filtering

Use query parameters for filters:

GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01

Input/Output Separation

Separate what the caller provides from what the system returns:

// Input: what the caller provides
type CreateTaskInput = {
  readonly title: string;
  readonly description?: string;
};

// Output: includes server-generated fields
type Task = {
  readonly id: TaskId;
  readonly title: string;
  readonly description: string | null;
  readonly createdAt: Date;
  readonly updatedAt: Date;
  readonly createdBy: UserId;
};

Common Rationalizations

RationalizationReality
"We'll document the API later"The types ARE the documentation. Define them first.
"We don't need pagination for now"You will the moment someone has 100+ items. Add it from the start.
"PATCH is complicated, let's just use PUT"PUT requires the full object every time. PATCH is what clients actually want.
"We'll version the API when we need to"Breaking changes without versioning break consumers. Design for extension from the start.
"Nobody uses that undocumented behavior"Hyrum's Law: if it's observable, somebody depends on it.
"Internal APIs don't need contracts"Internal consumers are still consumers. Contracts prevent coupling and enable parallel work.
"Retries are the client's problem"Without idempotency, retries create duplicates. Design for at-least-once delivery.
"We'll add rate limiting later"By then, clients have built around unlimited access. Rate limits are part of the contract.
"Error messages are just for debugging"Errors are part of your API's developer experience. Make them actionable, not diagnostic.

Red Flags

  • Endpoints that return different shapes depending on conditions
  • Inconsistent error formats across endpoints
  • Error responses that expose stack traces or internal paths
  • Breaking changes to existing fields (type changes, removals)
  • List endpoints without pagination
  • Verbs in REST URLs (/api/createTask, /api/getUsers)
  • Third-party API responses used without validation
  • No typed input/output schemas for endpoints
  • POST endpoints without idempotency handling for state-changing operations
  • No rate limit headers on responses
  • Retry logic without exponential backoff
  • Missing browser security headers on API responses (X-Content-Type-Options, CSP, Referrer-Policy)
  • Custom X- prefixed headers (deprecated by RFC 6648)

Verification

After designing an API:

  • [ ] Every endpoint has typed input and output schemas
  • [ ] Error responses follow a single consistent format (RFC 9457 for public APIs, or a simpler consistent shape for internal APIs)
  • [ ] Error responses never leak implementation details (stack traces, internal paths)
  • [ ] Validation happens at system boundaries only
  • [ ] List endpoints support pagination
  • [ ] New fields are additive and optional (backward compatible)
  • [ ] Naming follows consistent conventions across all endpoints
  • [ ] Contract defined before implementation (contract-first)
  • [ ] POST endpoints that create resources or change state have idempotency handling
  • [ ] Rate limit headers included on responses
  • [ ] Content-Type is application/problem+json for RFC 9457 responses, application/json for simpler formats
  • [ ] Browser security headers on all responses (X-Content-Type-Options: nosniff, CSP: default-src 'none', Referrer-Policy: no-referrer)
  • [ ] Caching strategy defined (explicit Cache-Control, ETags for revalidation, Vary where needed)

平台分布

Codex

37.11%
按下载量换算41

Claude

28.65%
按下载量换算32

Cursor

18.76%
按下载量换算21

Gemini CLI

8.22%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

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

继续浏览同类 Skills