Agent skill

API Design

by affaan-m in affaan-m/ECC

REST API设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和生产API的速率限制. An agent skill from affaan-m/ECC.

MITAuto-check passedBackend & APIs

Install API Design

skills CLI
$ npx skills add affaan-m/ECC --skill api-design -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install affaan-m/ECC api-design --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/affaan-m/ECC.git skills-src && mkdir -p .claude/skills && cp -r skills-src/docs/zh-CN/skills/api-design .claude/skills/api-design && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
api-design
GitHub stars
276k
Used in
3 other repos
Token cost
~2.6k tokens
SKILL.md length
186 words
Files
1
Skills in repo
673
Repo updated
First seen
Licence
MIT

At a glance

REST API设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和生产API的速率限制. An agent skill from affaan-m/ECC.

  • Tasks that involve API design
  • SKILL.md covers 何时启用, 资源设计, HTTP 方法和状态码 and 响应格式, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Tasks that involve REST APIs

What it does

API Design is an agent skill from affaan-m/ECC. REST API设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和生产API的速率限制。

Its SKILL.md is about 2.6k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering API design and REST APIs. The repository describes itself as: The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. The licence is MIT.

When your agent uses it

  • Tasks that involve API design
  • Tasks that involve REST APIs

Example prompts

  • “/api-design”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit ef648e0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are json, typescript, python and go).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

API Design loads about 2.6k tokens when it runs. Until then it costs about 16 tokens; SKILL.md has 186 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~16
When it runs · the whole SKILL.md, loaded when a task matches
~2.6k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from affaan-m/ECC at commit ef648e0, republished under its MIT licence (© affaan-m). 186 words, ~2,565 tokens.

Download SKILL.mdSave it as .claude/skills/api-design/SKILL.md (or your agent's skills folder).
name
api-design
description
REST API设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和生产API的速率限制。
origin
ECC

API 设计模式

用于设计一致、对开发者友好的 REST API 的约定和最佳实践。

何时启用

  • 设计新的 API 端点时
  • 审查现有的 API 契约时
  • 添加分页、过滤或排序功能时
  • 为 API 实现错误处理时
  • 规划 API 版本策略时
  • 构建面向公众或合作伙伴的 API 时

资源设计

URL 结构
# 资源使用名词、复数、小写、短横线连接
GET    /api/v1/users
GET    /api/v1/users/:id
POST   /api/v1/users
PUT    /api/v1/users/:id
PATCH  /api/v1/users/:id
DELETE /api/v1/users/:id

# 用于关系的子资源
GET    /api/v1/users/:id/orders
POST   /api/v1/users/:id/orders

# 非 CRUD 映射的操作(谨慎使用动词)
POST   /api/v1/orders/:id/cancel
POST   /api/v1/auth/login
POST   /api/v1/auth/refresh
命名规则
# 良好
/api/v1/team-members          # 多单词资源使用 kebab-case
/api/v1/orders?status=active  # 查询参数用于过滤
/api/v1/users/123/orders      # 嵌套资源表示所有权关系

# 不良
/api/v1/getUsers              # URL 中包含动词
/api/v1/user                  # 使用单数形式(应使用复数)
/api/v1/team_members          # URL 中使用 snake_case
/api/v1/users/123/getOrders   # 嵌套资源路径中包含动词

HTTP 方法和状态码

方法语义
方法幂等性安全性用途
GET是是检索资源
POST否否创建资源,触发操作
PUT是否完全替换资源
PATCH否*否部分更新资源
DELETE是否删除资源

*通过适当的实现,PATCH 可以实现幂等

状态码参考
# 成功
200 OK                    — GET、PUT、PATCH(包含响应体)
201 Created               — POST(包含 Location 头部)
204 No Content            — DELETE、PUT(无响应体)

# 客户端错误
400 Bad Request           — 验证失败、JSON 格式错误
401 Unauthorized          — 缺少或无效的身份验证
403 Forbidden             — 已认证但未授权
404 Not Found             — 资源不存在
409 Conflict              — 重复条目、状态冲突
422 Unprocessable Entity  — 语义无效(JSON 格式正确但数据错误)
429 Too Many Requests     — 超出速率限制

# 服务器错误
500 Internal Server Error — 意外故障(切勿暴露细节)
502 Bad Gateway           — 上游服务失败
503 Service Unavailable   — 临时过载,需包含 Retry-After 头部
常见错误
# 错误:对所有请求都返回 200
{ "status": 200, "success": false, "error": "Not found" }

# 正确:按语义使用 HTTP 状态码
HTTP/1.1 404 Not Found
{ "error": { "code": "not_found", "message": "User not found" } }

# 错误:验证错误返回 500
# 正确:返回 400 或 422 并包含字段级详情

# 错误:创建资源返回 200
# 正确:返回 201 并包含 Location 标头
HTTP/1.1 201 Created
Location: /api/v1/users/abc-123

响应格式

成功响应
json
{
  "data": {
    "id": "abc-123",
    "email": "alice@example.com",
    "name": "Alice",
    "created_at": "2025-01-15T10:30:00Z"
  }
}
集合响应(带分页)
json
{
  "data": [
    { "id": "abc-123", "name": "Alice" },
    { "id": "def-456", "name": "Bob" }
  ],
  "meta": {
    "total": 142,
    "page": 1,
    "per_page": 20,
    "total_pages": 8
  },
  "links": {
    "self": "/api/v1/users?page=1&per_page=20",
    "next": "/api/v1/users?page=2&per_page=20",
    "last": "/api/v1/users?page=8&per_page=20"
  }
}
错误响应
json
{
  "error": {
    "code": "validation_error",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address",
        "code": "invalid_format"
      },
      {
        "field": "age",
        "message": "Must be between 0 and 150",
        "code": "out_of_range"
      }
    ]
  }
}
响应包装器变体
typescript
// Option A: Envelope with data wrapper (recommended for public APIs)
interface ApiResponse<T> {
  data: T;
  meta?: PaginationMeta;
  links?: PaginationLinks;
}

interface ApiError {
  error: {
    code: string;
    message: string;
    details?: FieldError[];
  };
}

// Option B: Flat response (simpler, common for internal APIs)
// Success: just return the resource directly
// Error: return error object
// Distinguish by HTTP status code

分页

基于偏移量(简单)
GET /api/v1/users?page=2&per_page=20

# 实现
SELECT * FROM users
ORDER BY created_at DESC
LIMIT 20 OFFSET 20;

优点: 易于实现,支持“跳转到第 N 页” 缺点: 在大偏移量时速度慢(例如 OFFSET 100000),并发插入时结果不一致

基于游标(可扩展)
GET /api/v1/users?cursor=eyJpZCI6MTIzfQ&limit=20

# 实现
SELECT * FROM users
WHERE id > :cursor_id
ORDER BY id ASC
LIMIT 21;  -- 多取一条以判断是否有下一页
json
{
  "data": [...],
  "meta": {
    "has_next": true,
    "next_cursor": "eyJpZCI6MTQzfQ"
  }
}

优点: 无论位置如何,性能一致;在并发插入时结果稳定 缺点: 无法跳转到任意页面;游标是不透明的

何时使用哪种
用例分页类型
管理仪表板,小数据集 (<10K)偏移量
无限滚动,信息流,大数据集游标
公共 API游标(默认)配合偏移量(可选)
搜索结果偏移量(用户期望有页码)

过滤、排序和搜索

过滤
# 简单相等
GET /api/v1/orders?status=active&customer_id=abc-123

# 比较运算符(使用括号表示法)
GET /api/v1/products?price[gte]=10&price[lte]=100
GET /api/v1/orders?created_at[after]=2025-01-01

# 多个值(逗号分隔)
GET /api/v1/products?category=electronics,clothing

# 嵌套字段(点表示法)
GET /api/v1/orders?customer.country=US
排序
# 单字段排序(前缀 - 表示降序)
GET /api/v1/products?sort=-created_at

# 多字段排序(逗号分隔)
GET /api/v1/products?sort=-featured,price,-created_at
全文搜索
# 搜索查询参数
GET /api/v1/products?q=wireless+headphones

# 字段特定搜索
GET /api/v1/users?email=alice
稀疏字段集
# 仅返回指定字段(减少负载)
GET /api/v1/users?fields=id,name,email
GET /api/v1/orders?fields=id,total,status&include=customer.name

认证和授权

基于令牌的认证
# Bearer token in Authorization header
GET /api/v1/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

# API key (for server-to-server)
GET /api/v1/data
X-API-Key: sk_live_abc123
授权模式
typescript
// Resource-level: check ownership
app.get("/api/v1/orders/:id", async (req, res) => {
  const order = await Order.findById(req.params.id);
  if (!order) return res.status(404).json({ error: { code: "not_found" } });
  if (order.userId !== req.user.id) return res.status(403).json({ error: { code: "forbidden" } });
  return res.json({ data: order });
});

// Role-based: check permissions
app.delete("/api/v1/users/:id", requireRole("admin"), async (req, res) => {
  await User.delete(req.params.id);
  return res.status(204).send();
});

速率限制

响应头
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000000

# 超出限制时
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Try again in 60 seconds."
  }
}
速率限制层级
层级限制时间窗口用例
匿名用户30/分钟每个 IP公共端点
认证用户100/分钟每个用户标准 API 访问
高级用户1000/分钟每个 API 密钥付费 API 套餐
内部服务10000/分钟每个服务服务间调用

版本控制

URL 路径版本控制(推荐)
/api/v1/users
/api/v2/users

优点: 明确,易于路由,可缓存 缺点: 版本间 URL 会变化

请求头版本控制
GET /api/users
Accept: application/vnd.myapp.v2+json

优点: URL 简洁 缺点: 测试更困难,容易忘记

版本控制策略
1. 从 /api/v1/ 开始 —— 除非必要,否则不要急于版本化
2. 最多同时维护 2 个活跃版本(当前版本 + 前一个版本)
3. 弃用时间线:
   - 宣布弃用(公共 API 需提前 6 个月通知)
   - 添加 Sunset 响应头:Sunset: Sat, 01 Jan 2026 00:00:00 GMT
   - 在弃用日期后返回 410 Gone 状态
4. 非破坏性变更无需创建新版本:
   - 向响应中添加新字段
   - 添加新的可选查询参数
   - 添加新的端点
5. 破坏性变更需要创建新版本:
   - 移除或重命名字段
   - 更改字段类型
   - 更改 URL 结构
   - 更改身份验证方法

实现模式

TypeScript (Next.js API 路由)
typescript
import { z } from "zod";
import { NextRequest, NextResponse } from "next/server";

const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

export async function POST(req: NextRequest) {
  const body = await req.json();
  const parsed = createUserSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json({
      error: {
        code: "validation_error",
        message: "Request validation failed",
        details: parsed.error.issues.map(i => ({
          field: i.path.join("."),
          message: i.message,
          code: i.code,
        })),
      },
    }, { status: 422 });
  }

  const user = await createUser(parsed.data);

  return NextResponse.json(
    { data: user },
    {
      status: 201,
      headers: { Location: `/api/v1/users/${user.id}` },
    },
  );
}
Python (Django REST Framework)
python
from rest_framework import serializers, viewsets, status
from rest_framework.response import Response

class CreateUserSerializer(serializers.Serializer):
    email = serializers.EmailField()
    name = serializers.CharField(max_length=100)

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "email", "name", "created_at"]

class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == "create":
            return CreateUserSerializer
        return UserSerializer

    def create(self, request):
        serializer = CreateUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = UserService.create(**serializer.validated_data)
        return Response(
            {"data": UserSerializer(user).data},
            status=status.HTTP_201_CREATED,
            headers={"Location": f"/api/v1/users/{user.id}"},
        )
Go (net/http)
go
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
    var req CreateUserRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        writeError(w, http.StatusBadRequest, "invalid_json", "Invalid request body")
        return
    }

    if err := req.Validate(); err != nil {
        writeError(w, http.StatusUnprocessableEntity, "validation_error", err.Error())
        return
    }

    user, err := h.service.Create(r.Context(), req)
    if err != nil {
        switch {
        case errors.Is(err, domain.ErrEmailTaken):
            writeError(w, http.StatusConflict, "email_taken", "Email already registered")
        default:
            writeError(w, http.StatusInternalServerError, "internal_error", "Internal error")
        }
        return
    }

    w.Header().Set("Location", fmt.Sprintf("/api/v1/users/%s", user.ID))
    writeJSON(w, http.StatusCreated, map[string]any{"data": user})
}

API 设计清单

发布新端点前请检查:

  • [ ] 资源 URL 遵循命名约定(复数、短横线连接、不含动词)
  • [ ] 使用了正确的 HTTP 方法(GET 用于读取,POST 用于创建等)
  • [ ] 返回了适当的状态码(不要所有情况都返回 200)
  • [ ] 使用模式(Zod, Pydantic, Bean Validation)验证了输入
  • [ ] 错误响应遵循带代码和消息的标准格式
  • [ ] 列表端点实现了分页(游标或偏移量)
  • [ ] 需要认证(或明确标记为公开)
  • [ ] 检查了授权(用户只能访问自己的资源)
  • [ ] 配置了速率限制
  • [ ] 响应未泄露内部细节(堆栈跟踪、SQL 错误)
  • [ ] 与现有端点命名一致(camelCase 对比 snake_case)
  • [ ] 已记录(更新了 OpenAPI/Swagger 规范)

© affaan-m, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in docs/zh-CN/skills/api-design of affaan-m/ECC.

Open the folder on GitHubat commit ef648e0

Used in 3 other repositories

We found 3 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 3 other GitHub owners. This page covers the copy in affaan-m/ECC, which our catalogue first saw on October 9, 2026.

Compare with similar skills

API Design next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

API Design compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
API Design this skillaffaan-m/ECC276k3 repos~2.6kAutomated safety check: PassMIT
Nodejs Backend Patternsever-works/ever-works16218 repos~4kAutomated safety check: PassAGPL-3.0
API DesignerJeffallan/claude-skills12k1 repos~2kAutomated safety check: PassMIT
Pangolin CRUD Endpointsfosrl/pangolin23k—~461Automated safety check: PassCustom licence
Old Coder API DesignAmazingAng/old-coder749—~3.4kAutomated safety check: PassMIT
Backend FundamentalsDanielPodolsky/ownyourcode2901 repos~1.1kAutomated safety check: PassMIT

Similar skills

  • Nodejs Backend Patterns

    ever-works/ever-works

    Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices.

    162 GitHub starsUsed in 18 repos~4k tokens
    Backend & APIsAuto-check passed
  • API Designer

    Jeffallan/claude-skills

    Designs REST and GraphQL APIs from resource modeling to an OpenAPI 3.1 contract, with versioning, pagination and RFC 7807 error handling.

    12k GitHub starsUsed in 1 repo~2k tokens
    Backend & APIsAuto-check passed
  • Use whenever asked to add, create, or scaffold a CRUD endpoint, router, or entity in this repo's server (create/list/get/update/delete handlers, new…

    23k GitHub stars~461 tokensUpdated today
    Backend & APIsAuto-check passed
  • Old Coder API Design

    AmazingAng/old-coder

    Reviews or designs an HTTP/JSON API's endpoints, auth, pagination, versioning and deprecations, guarding against inventing a bespoke interface or silently breaking consumers.

    749 GitHub stars~3.4k tokensUpdated 1 mo ago
    Backend & APIsAuto-check passed
  • Backend Fundamentals

    DanielPodolsky/ownyourcode

    Reviews API design, REST conventions, and backend architecture.

    290 GitHub starsUsed in 1 repo~1.1k tokens
    Backend & APIsAuto-check passed
  • API Design Safety

    doccker/cc-use-exp

    当设计或修改 REST API 响应结构、处理 API 返回值,或生成 Excel/CSV/PDF/对账文件等下游产物时触发。防止 API 设计缺陷导致的字段错位、类型歧义,以及生成产物时关键字段缺失但静默成功的问题。

    1.1k GitHub stars~2.6k tokensUpdated 1 mo ago
    Backend & APIsAuto-check passed

More from affaan-m/ECC

All 673 skills in this repo
  • Skill Stocktake

    affaan-m/ECC

    Audits your installed Claude skills and commands for quality, with a quick mode for recently changed skills and a full mode that evaluates all of them through subagents.

    276k GitHub starsUsed in 5 repos~1.9k tokens
    Auto-check passed
  • Ingests, indexes, searches, edits and monitors video, audio and live streams through the VideoDB Python SDK, returning stream links, clips and timestamps.

    276k GitHub starsUsed in 3 repos~3.5k tokens
    Auto-check: notes
  • Rules Distillation

    affaan-m/ECC

    Scans installed skills for principles that recur across them and proposes rule-file changes: append, revise, add a section, create a file or leave as covered.

    276k GitHub starsUsed in 2 repos~2.3k tokens
    Auto-check passed
  • Builds DRAFT counterparty agreements from one markdown template and a small JSON spec per party, with clauses picked by the party's role.

    276k GitHub stars~2.9k tokensUpdated 4 days ago
    Auto-check passed
  • Measures whether agents actually follow a skill, rule or agent definition by generating scenarios at three strictness levels and scoring tool-call traces.

    276k GitHub starsUsed in 1 repo~623 tokens
    Auto-check passed
  • Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.

    276k GitHub stars~3.5k tokensUpdated 4 days ago
    Auto-check passed

Categories

Questions about API Design

What does API Design do?

REST API设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和生产API的速率限制. An agent skill from affaan-m/ECC. API Design is an agent skill from affaan-m/ECC.

When should I use API Design?

API Design fits situations like: tasks that involve API design; tasks that involve REST APIs.

How do I install API Design in Claude Code?

Run `npx skills add affaan-m/ECC --skill api-design -a claude-code`. Or copy the skill folder (docs/zh-CN/skills/api-design in affaan-m/ECC) into .claude/skills/api-design in your project. Claude Code loads it when a task matches its description.

How do I install API Design in Codex?

Run `npx skills add affaan-m/ECC --skill api-design -a codex`. Or copy the skill folder (docs/zh-CN/skills/api-design in affaan-m/ECC) into .agents/skills/api-design in your project. Codex loads it when a task matches its description.

Can I use API Design in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add affaan-m/ECC --skill api-design -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/api-design, .gemini/skills/api-design, .github/skills/api-design and .opencode/skills/api-design in your project.

What does API Design need to run?

SKILL.md names no scripts, command-line tools or credentials: API Design is instructions for the agent only. Our summary lists: Python 3.

Does API Design access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is API Design safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does API Design use?

API Design is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does API Design use?

About 2.6k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to API Design?

Skills that share tags, products or a category with API Design: Nodejs Backend Patterns (ever-works/ever-works, 162 stars), API Designer (Jeffallan/claude-skills, 12k stars), Pangolin CRUD Endpoints (fosrl/pangolin, 23k stars) and Old Coder API Design (AmazingAng/old-coder, 749 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains API Design?

affaan-m (a GitHub user) maintains it in affaan-m/ECC, which has 275,546 GitHub stars. The repository holds 673 skills in this directory. The repository was last updated on October 5, 2026.

Source: affaan-m/ECC on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.