Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计通过

api-designAPI 设计

Agent Skill

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

总安装

1,717

周安装

73

GitHub Stars

12

下载量

602
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

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

简介

api-design 用于辅助 API 设计、接口文档和请求响应结构梳理。

  • 适合生成 OpenAPI 草稿、检查字段命名或整理错误码。
  • 通过 npx skills add 命令从指定仓库安装并使用该技能。
  • 使用时需确认真实业务语义、鉴权方式和分页规则,避免凭空补字段。
  • 最好从现有代码或接口样例中提取事实,确保接口定义准确。

SKILL.md

Good API design makes the right thing easy and the wrong thing hard. This skill helps you create APIs that are a pleasure to use and maintain.

<quick_start> Resource naming: Nouns, plural, lowercase, hyphenated (/users, /blog-posts)

HTTP methods: GET (read), POST (create), PUT (replace), PATCH (update), DELETE (remove)

Status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Rate Limited

Pagination: Prefer cursor-based for real-time data; use ?limit=20&cursor=xxx

Versioning: URL path (/api/v1/) is clearest approach </quick_start>

<success_criteria> API design is successful when:

  • Resources use plural nouns with consistent naming
  • HTTP methods match semantics (GET=read, POST=create, etc.)
  • Error responses follow consistent format with code, message, details, requestId
  • Pagination implemented (cursor or offset based)
  • Rate limiting headers included (X-RateLimit-Limit, Remaining, Reset)
  • Versioning strategy defined before breaking changes needed </success_criteria>

<core_principles>

API Design Principles

  1. Consistency - Same patterns everywhere (naming, errors, pagination)
  2. Predictability - Developers can guess how things work
  3. Simplicity - Easy cases should be easy, complex cases possible
  4. Backwards compatibility - Don't break existing clients
  5. Self-documenting - Clear naming, helpful error messages </core_principles>

<rest_basics>

RESTful Conventions

Resource Naming

# GOOD: Nouns, plural, lowercase, hyphenated
GET    /users
GET    /users/{id}
GET    /users/{id}/posts
GET    /blog-posts
GET    /api/v1/user-preferences

# BAD: Verbs, singular, mixed case, underscores
GET    /getUser
GET    /user/{id}
GET    /User/{id}/getPosts
GET    /blog_posts

HTTP Methods

MethodPurposeIdempotentSafeRequest Body
GETRead resourceYesYesNo
POSTCreate resourceNoNoYes
PUTReplace resourceYesNoYes
PATCHPartial updateNo*NoYes
DELETERemove resourceYesNoNo

*PATCH is idempotent if you apply the same patch

CRUD Operations

# Collection operations
GET    /users           # List all users
POST   /users           # Create a user

# Single resource operations
GET    /users/{id}      # Get one user
PUT    /users/{id}      # Replace user
PATCH  /users/{id}      # Update user fields
DELETE /users/{id}      # Delete user

# Nested resources
GET    /users/{id}/posts       # User's posts
POST   /users/{id}/posts       # Create post for user
GET    /posts/{id}/comments    # Post's comments

Actions (Non-CRUD Operations)

# When you need actions, use verbs as sub-resources
POST   /users/{id}/activate
POST   /users/{id}/deactivate
POST   /orders/{id}/cancel
POST   /invoices/{id}/send
POST   /auth/login
POST   /auth/logout
POST   /auth/refresh

Status Codes

CodeMeaningWhen to Use
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST that creates
204No ContentSuccessful DELETE
400Bad RequestInvalid input, validation error
401UnauthorizedMissing/invalid authentication
403ForbiddenAuthenticated but not authorized
404Not FoundResource doesn't exist
409ConflictDuplicate, state conflict
422UnprocessableValidation failed (alternative to 400)
429Too Many RequestsRate limited
500Server ErrorUnexpected server error
</rest_basics>

<error_handling>

Error Responses

Consistent Error Format

// Standard error response
interface ErrorResponse {
  error: {
    code: string;           // Machine-readable code
    message: string;        // Human-readable message
    details?: ErrorDetail[]; // Field-level errors
    requestId?: string;     // For support/debugging
  };
}

interface ErrorDetail {
  field: string;
  message: string;
  code: string;
}

Examples

// 400 Bad Request - Validation error
{
  "error": {
    "code": "validation_error",
    "message": "Invalid request parameters",
    "details": [
      { "field": "email", "message": "Invalid email format", "code": "invalid_format" },
      { "field": "age", "message": "Must be at least 13", "code": "min_value" }
    ],
    "requestId": "req_abc123"
  }
}

// 401 Unauthorized
{
  "error": {
    "code": "unauthorized",
    "message": "Invalid or expired authentication token",
    "requestId": "req_abc123"
  }
}

// 403 Forbidden
{
  "error": {
    "code": "forbidden",
    "message": "You don't have permission to access this resource",
    "requestId": "req_abc123"
  }
}

// 404 Not Found
{
  "error": {
    "code": "not_found",
    "message": "User not found",
    "requestId": "req_abc123"
  }
}

// 429 Rate Limited
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please retry after 60 seconds",
    "requestId": "req_abc123"
  }
}

Implementation

// Error class
class ApiError extends Error {
  constructor(
    public statusCode: number,
    public code: string,
    message: string,
    public details?: ErrorDetail[]
  ) {
    super(message);
  }
}

// Error handler middleware
function errorHandler(error: Error, req: Request, res: Response) {
  const requestId = req.headers['x-request-id'] || crypto.randomUUID();

  if (error instanceof ApiError) {
    return res.status(error.statusCode).json({
      error: {
        code: error.code,
        message: error.message,
        details: error.details,
        requestId,
      },
    });
  }

  // Log unexpected errors
  logger.error('Unexpected error', { error, requestId });

  // Don't expose internal details
  return res.status(500).json({
    error: {
      code: 'internal_error',
      message: 'An unexpected error occurred',
      requestId,
    },
  });
}

</error_handling>

Cursor-Based (Recommended)

// Request
GET /posts?limit=20&cursor=eyJpZCI6MTAwfQ

// Response
{
  "data": [...],
  "pagination": {
    "hasMore": true,
    "nextCursor": "eyJpZCI6MTIwfQ",
    "prevCursor": "eyJpZCI6MTAwfQ"
  }
}

Pros: Consistent results, handles real-time data Cons: Can't jump to page N

Offset-Based

// Request
GET /posts?page=2&limit=20
// or
GET /posts?offset=20&limit=20

// Response
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 150,
    "totalPages": 8
  }
}

Pros: Can jump to any page Cons: Inconsistent with real-time data, slow on large tables

Implementation (Cursor)

// Encode/decode cursor
function encodeCursor(data: object): string {
  return Buffer.from(JSON.stringify(data)).toString('base64url');
}

function decodeCursor(cursor: string): object {
  return JSON.parse(Buffer.from(cursor, 'base64url').toString());
}

// Query with cursor
async function getPosts(limit: number, cursor?: string) {
  const where: any = {};

  if (cursor) {
    const { id } = decodeCursor(cursor);
    where.id = { lt: id };
  }

  const posts = await db.post.findMany({
    where,
    orderBy: { id: 'desc' },
    take: limit + 1, // Fetch one extra to check hasMore
  });

  const hasMore = posts.length > limit;
  const data = hasMore ? posts.slice(0, -1) : posts;

  return {
    data,
    pagination: {
      hasMore,
      nextCursor: hasMore ? encodeCursor({ id: data[data.length - 1].id }) : null,
    },
  };
}

Use query params: ?status=active, ?sort=-created_at (prefix - for desc), ?fields=id,name,email. Validate with Zod schema, build Prisma where clause from parsed filters.

See reference/filtering-sorting.md for full query parameter patterns and implementation.

URL Path Versioning (Recommended)

GET /api/v1/users
GET /api/v2/users

Pros: Clear, easy to understand Cons: More maintenance

Header Versioning

GET /api/users
Accept: application/vnd.api+json; version=2

Pros: Clean URLs Cons: Hidden, harder to test

When to Version

Create a new version when:

  • Removing fields from responses
  • Changing field types or formats
  • Removing endpoints
  • Changing authentication

Don't create a new version for:

  • Adding new optional fields
  • Adding new endpoints
  • Adding new optional parameters
  • Bug fixes

<rate_limiting>

Rate Limiting

Include headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. Return 429 with Retry-After when exceeded. Use sliding window algorithm (e.g., @upstash/ratelimit).

See reference/rate-limiting.md for tier definitions and implementation. </rate_limiting>

TopicReference FileWhen to Load
REST patternsreference/rest-patterns.mdEndpoint design
Error handlingreference/error-handling.mdError responses
Paginationreference/pagination.mdList endpoints
Filtering & sortingreference/filtering-sorting.mdQuery parameters
Rate limitingreference/rate-limiting.mdThrottling
Versioningreference/versioning.mdAPI evolution
Documentationreference/documentation.mdOpenAPI, docs
Checklistreference/checklist.mdPre-launch validation

To load: Ask for the specific topic or check if context suggests it.

Emit Outcome Sidecar

As the final step, write to ~/.claude/skill-analytics/last-outcome-api-design.json:

{"ts":"[UTC ISO8601]","skill":"api-design","version":"1.0.0","variant":"default",
 "status":"[success|partial|error]","runtime_ms":[estimated ms from start],
 "metrics":{"endpoints_designed":[n],"patterns_applied":[n]},
 "error":null,"session_id":"[YYYY-MM-DD]"}

Use status "partial" if some stages failed but results were produced. Use "error" only if no output was generated.

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

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

平台分布

Claude Code

29.35%
按下载量换算177

Antigravity

20.49%
按下载量换算123

Gemini CLI

16.29%
按下载量换算98

Codex

11.91%
按下载量换算72

OpenCode

8.4%
按下载量换算51

windsurf

3.41%
按下载量换算21

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills