AgentSkillsCN

api-design

当用户提及“API”、“端点”、“REST”、“GraphQL”、“路由”、“请求”、“响应”、“后端”,或询问如何设计 Web 服务接口时,可选用此技能。

SKILL.md
--- frontmatter
name: api-design
description: When the user mentions "API", "endpoint", "REST", "GraphQL", "route", "request", "response", "backend", or asks about designing web service interfaces.

API Design Guide

Design Principles

  1. Consistency - Same patterns everywhere
  2. Predictability - Clients can guess behavior
  3. Simplicity - Easy to use correctly, hard to misuse
  4. Evolvability - Can change without breaking clients

REST API Design

URL Structure

code
/resources                    # Collection
/resources/{id}               # Single resource
/resources/{id}/sub-resources # Nested resources

Good:

  • /users/123/orders
  • /products?category=electronics
  • /search?q=keyword

Bad:

  • /getUser/123
  • /users/123/getOrders
  • /api/v1/fetch-all-products

HTTP Methods

MethodUse CaseIdempotent
GETReadYes
POSTCreateNo
PUTReplaceYes
PATCHPartial updateYes
DELETERemoveYes

Status Codes

CodeMeaningWhen to Use
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST
204No ContentSuccessful DELETE
400Bad RequestInvalid input
401UnauthorizedNot authenticated
403ForbiddenNot authorized
404Not FoundResource doesn't exist
409ConflictState conflict (duplicate)
422UnprocessableValidation failed
500Server ErrorUnexpected error

Response Format

json
{
  "data": { ... },
  "meta": {
    "page": 1,
    "total": 100
  }
}

Error response:

json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Email is required",
    "details": [
      { "field": "email", "message": "Required" }
    ]
  }
}

Pagination

Offset-based:

code
/items?page=2&limit=20

Cursor-based (preferred for large datasets):

code
/items?cursor=abc123&limit=20

Filtering & Sorting

code
/products?category=electronics&minPrice=100
/products?sort=price&order=desc
/products?fields=id,name,price

Versioning Strategies

StrategyExampleProsCons
URL path/v1/usersExplicit, cacheableURL pollution
HeaderAccept-Version: v1Clean URLsLess visible
Query param?version=1Easy to testCache issues

Recommendation: URL path versioning for simplicity.

Authentication

MethodUse Case
API KeyServer-to-server, simple
JWTStateless, distributed
OAuth 2.0Third-party access
SessionTraditional web apps

Rate Limiting

Include headers:

code
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000000

Documentation Requirements

Every endpoint needs:

  • URL and method
  • Authentication required?
  • Request parameters (path, query, body)
  • Response format with examples
  • Error codes and meanings
  • Rate limits

Common Mistakes

  • Using verbs in URLs (/getUsers)
  • Inconsistent naming (/users vs /Users)
  • Returning 200 for errors
  • No pagination on list endpoints
  • Breaking changes without versioning
  • Missing error details
  • No rate limiting