api-design

GitHub

提供REST和GraphQL API设计指南,涵盖一致性、资源导向、开发者体验及向后兼容原则。包含URL规范、HTTP方法映射、错误处理(RFC 7807)、分页、版本控制及文档标准的质量评分卡与最佳实践。

categories/backend/api-design/SKILL.md cosmicstack-labs/mercury-agent-skills

Trigger Scenarios

API接口设计规范咨询 RESTful URL路径优化 HTTP状态码选择建议 API版本控制策略 接口错误格式标准化

Install

npx skills add cosmicstack-labs/mercury-agent-skills --skill api-design -g -y
More Options

Non-standard path

npx skills add https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/backend/api-design -g -y

Use without installing

npx skills use cosmicstack-labs/mercury-agent-skills@api-design

指定 Agent (Claude Code)

npx skills add cosmicstack-labs/mercury-agent-skills --skill api-design -a claude-code -g -y

安装 repo 全部 skill

npx skills add cosmicstack-labs/mercury-agent-skills --all -g -y

预览 repo 内 skill

npx skills add cosmicstack-labs/mercury-agent-skills --list

SKILL.md

Frontmatter
{
    "name": "api-design",
    "metadata": {
        "tags": [
            "api",
            "rest",
            "graphql",
            "design",
            "documentation",
            "error-handling"
        ],
        "author": "cosmicstack-labs",
        "version": "1.0.0",
        "category": "backend"
    },
    "description": "REST and GraphQL API design principles, versioning, error handling, and documentation patterns"
}

API Design

Design APIs that are intuitive, consistent, and a joy to integrate with.

Core Principles

1. Consistency Over Cleverness

Your API should be predictable. If one resource uses POST /users, another shouldn't use POST /createUser. Patterns should be uniform across the entire surface.

2. Resources, Not Actions

URLs name resources. HTTP verbs name actions. /users is a resource. POST /users creates one. DELETE /users/123 removes one.

3. Developer Experience First

Your API's consumers are developers. Good DX means clear errors, thorough documentation, predictable responses, and sensible defaults.

4. Backward Compatibility

Once a field or endpoint is public, removing it breaks consumers. Version carefully. Add fields, don't remove them. Deprecate before deleting.


API Quality Scorecard

Dimension Poor Good Excellent
URL structure /getUsers, /create_user /users, POST /users /users, /users/:id, with HATEOAS links
HTTP methods All POST CRUD mapped properly Proper status codes, idempotency
Error format HTML or plain text JSON with message RFC 7807 Problem Details
Pagination None or offset Cursor-based Cursor + metadata + total hints
Versioning None URL prefix /v1/ Header or content negotiation
Documentation None Swagger/OpenAPI Interactive docs with examples
Rate limiting None X-RateLimit-* headers Granular per-endpoint limits

Target: Good for internal APIs. Excellent for public APIs.


Actionable Guidance

RESTful URL Design

Pattern: /{version}/{resource}[/{resource-id}][/{sub-resource}]

# Good
GET    /v1/users                    # List users
POST   /v1/users                    # Create user
GET    /v1/users/{id}               # Get user by ID
PATCH  /v1/users/{id}               # Partial update user
DELETE /v1/users/{id}               # Delete user
GET    /v1/users/{id}/orders        # List user's orders
GET    /v1/users/{id}/orders/{oid}  # Get specific order

# Bad
GET    /v1/getUserInfo              # Verb in URL
POST   /v1/createNewUser            # Verb, camelCase
PUT    /v1/updateUser               # Verb, vague
GET    /v1/users_list               # Underscore, not a resource
POST   /v1/delete_user/123          # POST for deletion, imperative style

Naming conventions:

  • Plural nouns: /users, /orders, /products
  • Lowercase with hyphens: /order-items, not /orderItems or /order_items
  • No file extensions: /users/123, not /users/123.json
  • No verbs in URLs: Use HTTP verbs for actions

HTTP Methods and Status Codes

Method Action Success Code Body Contains
GET Retrieve 200 OK Resource(s)
POST Create 201 Created Created resource
PUT Full replace 200 OK Replaced resource
PATCH Partial update 200 OK Updated resource
DELETE Remove 204 No Content (empty)

Common status codes:

Code Meaning When
200 OK Successful GET, PUT, PATCH
201 Created Successful POST
204 No Content Successful DELETE
400 Bad Request Malformed input, validation failure
401 Unauthorized Missing/invalid auth token
403 Forbidden Valid auth but insufficient permissions
404 Not Found Resource doesn't exist
409 Conflict Duplicate resource, version conflict
422 Unprocessable Semantic validation failure
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Unhandled server error

Error Response Format

Use RFC 7807 (Problem Details):

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/errors/validation-error",
  "title": "Validation Error",
  "status": 422,
  "detail": "The request body contains invalid fields.",
  "instance": "/v1/users",
  "errors": [
    {
      "field": "email",
      "message": "Must be a valid email address",
      "code": "INVALID_FORMAT"
    },
    {
      "field": "age",
      "message": "Must be a positive integer",
      "code": "OUT_OF_RANGE"
    }
  ]
}

Pagination

Cursor-based pagination (recommended for most APIs):

GET /v1/users?cursor=eyJpZCI6MTB9&limit=20

{
  "data": [...],
  "pagination": {
    "next_cursor": "eyJpZCI6MzB9",
    "has_more": true
  }
}

Offset-based (acceptable for small, stable datasets):

GET /v1/users?page=2&per_page=20

{
  "data": [...],
  "pagination": {
    "page": 2,
    "per_page": 20,
    "total": 154,
    "total_pages": 8
  }
}

Versioning

Strategy: URL prefix versioning (most common, clearest)

/v1/users
/v2/users

When to bump version:

  • Removing a field or endpoint
  • Changing response structure (e.g., renaming fields)
  • Changing request/response semantics
  • Changing authentication requirements

When NOT to bump version:

  • Adding new fields (consumers should ignore unknown fields)
  • Adding new endpoints
  • Bug fixes that don't change API contract

GraphQL Considerations

  • N+1 problem: Use DataLoader for batching
  • Auth at resolver level: Never in field-level middleware
  • Max query depth: Prevent runaway queries with depth limiting
  • Persisted queries: Use for production to reduce overhead
  • Nullable by default: Make fields nullable unless you're certain
type Query {
  user(id: ID!): User
}

type User {
  id: ID!
  name: String!
  email: String  # Nullable — might be hidden for privacy
  orders: [Order!]!  # Non-null list, but could be empty
}

API Documentation

OpenAPI 3.0 example:

openapi: "3.0.0"
paths:
  /v1/users:
    get:
      summary: List users
      parameters:
        - name: cursor
          in: query
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
      responses:
        "200":
          description: Paginated list of users
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/User" }
                  pagination:
                    $ref: "#/components/schemas/Pagination"

Common Mistakes

  1. Inconsistent error responses: Different endpoints returning different error shapes. Standardize on one format.
  2. Exposing internal IDs: Use opaque public IDs (UUIDs) instead of auto-increment integers.
  3. No pagination on list endpoints: Returning all records is a performance and reliability risk.
  4. PUT for partial updates: Use PATCH. PUT should replace the entire resource.
  5. Nesting too deep: /v1/users/{id}/orders/{oid}/items/{iid} — keep nesting to 2-3 levels max.
  6. Returning 500 for validation errors: Validation failures are client errors — use 400/422.
  7. No rate limiting headers: Tell clients their limits with headers. Don't just drop connections.
  8. Synchronous long operations: If an operation takes >5 seconds, use 202 Accepted with a status URL.

Version History

  • 38e2523 Current 2026-07-05 19:36

Same Skill Collection

categories/ai-ml/agent-audit-logging/SKILL.md
categories/ai-ml/agent-handoff-protocols/SKILL.md
categories/ai-ml/agent-health-monitoring/SKILL.md
categories/ai-ml/agent-task-delegation/SKILL.md
categories/ai-ml/ai-agent-design/SKILL.md
categories/ai-ml/error-recovery-retry/SKILL.md
categories/ai-ml/memory-management/SKILL.md
categories/ai-ml/prompt-engineering/SKILL.md
categories/ai-ml/prompt-version-management/SKILL.md
categories/ai-ml/token-budget-tracking/SKILL.md
categories/automation/daily-briefing/SKILL.md
categories/automation/screenshot/SKILL.md
categories/automation/shell-scripting/SKILL.md
categories/automation/twitter-account-manager/SKILL.md
categories/automation/workflow-automation/SKILL.md
categories/automation/x-twitter-automation/SKILL.md
categories/backend/authentication-authorization/SKILL.md
categories/backend/caching-strategies/SKILL.md
categories/backend/database-design/SKILL.md
categories/backend/message-queues/SKILL.md
categories/backend/microservices/SKILL.md
categories/backend/nodejs-patterns/SKILL.md
categories/backend/python-patterns/SKILL.md
categories/backend/serverless-patterns/SKILL.md
categories/business/event-staffing-compliance/SKILL.md
categories/business/event-staffing-ordering/SKILL.md
categories/business/negotiation/SKILL.md
categories/business/startup-strategy/SKILL.md
categories/career/career-planning/SKILL.md
categories/career/interview-prep/SKILL.md
categories/career/linkedin-optimization/SKILL.md
categories/career/resume-writing/SKILL.md
categories/career/salary-negotiation/SKILL.md
categories/creative-personal-development/content-repurposer/SKILL.md
categories/creative-personal-development/daily-standup-journal/SKILL.md
categories/creative-personal-development/decision-matrix/SKILL.md
categories/creative-personal-development/idea-validator/SKILL.md
categories/creative-personal-development/meeting-note-summarizer/SKILL.md
categories/creative-personal-development/personal-branding-statement/SKILL.md
categories/creative-personal-development/storytelling-advisor/SKILL.md
categories/creative-personal-development/time-blocking-scheduler/SKILL.md
categories/data/data-pipeline/SKILL.md
categories/design/accessibility/SKILL.md
categories/design/ui-design-system/SKILL.md
categories/development/api-documentation/SKILL.md
categories/development/architecture-decision-records/SKILL.md
categories/development/clean-code/SKILL.md
categories/development/code-review/SKILL.md
categories/development/debugging-mastery/SKILL.md
categories/development/dependency-management/SKILL.md
categories/development/documentation-generation/SKILL.md
categories/development/git-workflow/SKILL.md
categories/development/hyperframes-cli/SKILL.md
categories/development/hyperframes-media/SKILL.md
categories/development/knowledge-base/SKILL.md
categories/development/markdown-mastery/SKILL.md
categories/development/refactoring-patterns/SKILL.md
categories/development/technical-writing/SKILL.md
categories/development/testing-strategies/SKILL.md
categories/devops/ci-cd-pipeline/SKILL.md
categories/devops/cloud-architecture/SKILL.md
categories/devops/docker-patterns/SKILL.md
categories/devops/kubernetes-patterns/SKILL.md
categories/devops/monitoring-observability/SKILL.md
categories/devops/sre-practices/SKILL.md
categories/devops/terraform-iac/SKILL.md
categories/education-learning/assessment-design/SKILL.md
categories/education-learning/learning-science/SKILL.md
categories/education-learning/micro-learning/SKILL.md
categories/education-learning/teaching-methods/SKILL.md
categories/finance-legal/budgeting-forecasting/SKILL.md
categories/finance-legal/contract-review/SKILL.md
categories/finance-legal/financial-analysis/SKILL.md
categories/finance-legal/privacy-compliance/SKILL.md
categories/finance-legal/risk-management/SKILL.md
categories/frontend/component-design-systems/SKILL.md
categories/frontend/frontend-testing/SKILL.md
categories/frontend/nextjs-patterns/SKILL.md
categories/frontend/react-patterns/SKILL.md
categories/frontend/responsive-design/SKILL.md
categories/frontend/state-management/SKILL.md
categories/frontend/tailwind-css/SKILL.md
categories/frontend/web-performance/SKILL.md
categories/health-wellness/fitness-planning/SKILL.md
categories/health-wellness/habit-formation/SKILL.md
categories/health-wellness/mental-health/SKILL.md
categories/health-wellness/nutrition-planning/SKILL.md
categories/health-wellness/sleep-optimization/SKILL.md
categories/marketing/content-creation/SKILL.md
categories/marketing/local-business-growth/SKILL.md
categories/marketing/seo-strategy/SKILL.md
categories/media-download/audio-extraction/SKILL.md
categories/media-download/github-repo-promo/SKILL.md
categories/media-download/github-repo-tour/SKILL.md
categories/media-download/legal-downloading/SKILL.md
categories/media-download/playlist-archiver/SKILL.md
categories/media-download/video-downloader/SKILL.md
categories/mobile/android-kotlin-patterns/SKILL.md
categories/mobile/app-store-optimization/SKILL.md
categories/mobile/ios-swift-patterns/SKILL.md
categories/mobile/mobile-performance/SKILL.md
categories/mobile/react-native-patterns/SKILL.md
categories/pdf-generation/invoice-document-pdf/SKILL.md
categories/pdf-generation/markdown-to-pdf/SKILL.md
categories/pdf-generation/report-generation/SKILL.md
categories/pdf-generation/typesetting-latex/SKILL.md
categories/presentation/data-storytelling/SKILL.md
categories/presentation/pitch-deck-creation/SKILL.md
categories/presentation/presentation-automation/SKILL.md
categories/presentation/presentation-design/SKILL.md
categories/product/product-strategy/SKILL.md
categories/product/user-research/SKILL.md
categories/security/security-audit/SKILL.md
categories/shop-restaurant/amazon-assistant/SKILL.md
categories/shop-restaurant/daily-pulse/SKILL.md
categories/shop-restaurant/inventory-optimizer/SKILL.md
categories/shop-restaurant/menu-engineer/SKILL.md
categories/shop-restaurant/price-scout/SKILL.md
categories/shop-restaurant/review-responder/SKILL.md
categories/shop-restaurant/social-post/SKILL.md
categories/shop-restaurant/staff-scheduler/SKILL.md
categories/shop-restaurant/table-manager/SKILL.md
categories/shop-restaurant/zomato-order/SKILL.md
categories/testing-qa/accessibility-testing/SKILL.md
categories/testing-qa/api-testing/SKILL.md
categories/testing-qa/e2e-testing/SKILL.md
categories/testing-qa/performance-testing/SKILL.md
categories/testing-qa/test-strategy/SKILL.md
categories/ai-ml/gbrain-lite/SKILL.md
categories/development/hyperframes/SKILL.md
categories/pdf-generation/any2pdf/SKILL.md

Metadata

Files
0
Version
38e2523
Hash
7149b163
Indexed
2026-07-05 19:36

trang chủ - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-08 20:37
浙ICP备14020137号-1 $bản đồ khách truy cập$