AgentSkillsCN

api-design

REST与GraphQL API设计规范,包括URL模式、状态码、分页、错误格式以及版本控制。在设计新API、审查API契约,或向任何后端添加端点时使用此功能。

SKILL.md
--- frontmatter
name: api-design
description: REST and GraphQL API design conventions including URL patterns, status codes, pagination, error format, and versioning. Use when designing new APIs, reviewing API contracts, or adding endpoints to any backend.
metadata:
  version: "1.0"

API Design

Decision Tree

code
New API needed → What type?
    ├─ CRUD operations on resources → REST
    ├─ Complex queries, multiple resources in one call → GraphQL
    ├─ Real-time updates → WebSocket or SSE
    ├─ Internal microservice → gRPC or REST
    └─ Simple webhook/callback → REST POST

REST URL Conventions

code
GET    /resources              # List (with pagination)
GET    /resources/:id          # Get one
POST   /resources              # Create
PUT    /resources/:id          # Full replace
PATCH  /resources/:id          # Partial update
DELETE /resources/:id          # Delete

# Nested resources (one level max)
GET    /users/:id/posts        # User's posts

# Actions (when CRUD doesn't fit)
POST   /resources/:id/actions/publish

Rules:

  • Plural nouns, lowercase, hyphens for multi-word
  • No verbs in URLs (the HTTP method IS the verb)
  • Max one level of nesting

Status Codes

CodeWhen
200Success with body
201Created (POST)
204Success, no body (DELETE)
400Invalid request data
401Not authenticated
403Authenticated but not authorized
404Not found
409Conflict (duplicate, state conflict)
422Validation error
429Rate limited
500Server error

Error Response Format

json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Human-readable explanation",
    "details": [
      { "field": "email", "message": "must be a valid email address" }
    ]
  }
}

Pagination

code
# Offset-based (simple)
GET /resources?page=2&per_page=20

# Cursor-based (preferred for large datasets)
GET /resources?cursor=abc123&limit=20

Anti-Patterns

Anti-PatternFix
Verbs in URLs (/getUsers)HTTP methods (GET /users)
Singular nouns (/user/1)Plural (/users/1)
Deep nesting (/a/1/b/2/c/3)Max one level, use query params
200 with error bodyUse proper status codes
No pagination on listsAlways paginate, default limit
Exposing auto-increment IDsUUIDs for public APIs

For detailed patterns see: