[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75WJNJHBWPGDNX9ADFBA7FQ":3,"skill-same:01M75WJNJHBWPGDNX9ADFBA7FQ":100},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":59,"repositoryHtmlUrl":60,"repositoryHomepageUrl":6,"ownerHtmlUrl":61,"ownerBlogUrl":62,"ownerDescription":63,"updatedAt":64,"install":65,"resources":77},"01M75WJNJHBWPGDNX9ADFBA7FQ","api-design-patterns",null,"Comprehensive API design patterns covering REST, GraphQL, gRPC, versioning, authentication, and modern API best practices","aAAaqwq\u002Fopenclaw-team","aAAaqwq","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F163369189?v=4","01M75WCZBK64XMP4RKNQB2ZV08","Daniel Li","01M75WCZCCEHPJV69BNPNXJY9E",2,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: api-design-patterns\ndescription: Comprehensive API design patterns covering REST, GraphQL, gRPC, versioning, authentication, and modern API best practices\nlicense: Apache-2.0\ncompatibility: claude-code\nmetadata:\n  version: 1.0.0\n  category: universal\n  related_skills: [graphql, typescript, nodejs-backend, django, fastapi, flask]\n  token_budget:\n    entry_point: 85\n    full_content: 8500\n  self_contained: true\ntags: [api, rest, graphql, grpc, architecture, web, design-patterns]\nprogressive_disclosure:\n  entry_point:\n    summary: \"Comprehensive API design patterns covering REST, GraphQL, gRPC, versioning, authentication, and modern API best practices\"\n    when_to_use: \"When designing, implementing, or documenting APIs.\"\n    quick_start: \"1. Review the core concepts below. 2. Apply patterns to your use case. 3. Follow best practices for implementation.\"\n  references:\n    - authentication.md\n    - graphql-patterns.md\n    - grpc-patterns.md\n    - rest-patterns.md\n    - versioning-strategies.md\n---\n# API Design Patterns\n\nDesign robust, scalable APIs using proven patterns for REST, GraphQL, and gRPC with proper versioning, authentication, and error handling.\n\n## Quick Reference\n\n**API Style Selection**:\n- REST: Resource-based CRUD, simple clients, HTTP-native caching\n- GraphQL: Client-driven queries, complex data graphs, real-time subscriptions\n- gRPC: High-performance RPC, microservices, strong typing, streaming\n\n**Critical Patterns**:\n- Versioning: URI (`\u002Fv1\u002Fusers`), header (`Accept: application\u002Fvnd.api+json;version=1`), content negotiation\n- Pagination: Offset (simple), cursor (stable), keyset (performant)\n- Auth: OAuth2 (delegated), JWT (stateless), API keys (service-to-service)\n- Rate limiting: Token bucket, fixed window, sliding window\n- Idempotency: Idempotency keys, conditional requests, safe retry\n\n**See references\u002F for deep dives**: `rest-patterns.md`, `graphql-patterns.md`, `grpc-patterns.md`, `versioning-strategies.md`, `authentication.md`\n\n## Core Principles\n\n### Universal API Design Standards\n\nApply these principles across all API styles:\n\n**1. Consistency Over Cleverness**\n- Follow established conventions for your API style\n- Use predictable naming patterns (snake_case or camelCase, pick one)\n- Maintain consistent error response formats\n- Version breaking changes, never surprise clients\n\n**2. Design for Evolution**\n- Plan for versioning from day one\n- Use optional fields with sensible defaults\n- Deprecate gracefully with sunset dates\n- Document breaking vs non-breaking changes\n\n**3. Security by Default**\n- Require authentication unless explicitly public\n- Use HTTPS\u002FTLS for all production endpoints\n- Implement rate limiting and throttling\n- Validate and sanitize all inputs\n- Return minimal error details to clients\n\n**4. Developer Experience First**\n- Provide comprehensive documentation (OpenAPI, GraphQL schema)\n- Return meaningful error messages with actionable guidance\n- Use standard HTTP status codes correctly\n- Include request IDs for debugging\n- Offer SDKs and code generators\n\n## API Style Decision Tree\n\n### When to Choose REST\n\n✅ **Use REST when:**\n- Building CRUD-focused resource APIs\n- Clients need HTTP caching (ETags, Cache-Control)\n- Wide platform compatibility required (browsers, mobile, IoT)\n- Simple, stateless client-server model fits\n- Team familiar with HTTP\u002FREST conventions\n\n❌ **Avoid REST when:**\n- Complex data fetching with nested relationships (N+1 queries)\n- Real-time updates are primary use case\n- Need strong typing and code generation\n- High-performance RPC between microservices\n\n**Example Use Cases**: Public APIs, mobile backends, traditional web services\n\n### When to Choose GraphQL\n\n✅ **Use GraphQL when:**\n- Clients need flexible, client-driven queries\n- Complex data graphs with nested relationships\n- Multiple client types with different data needs\n- Real-time subscriptions required\n- Strong typing and schema validation needed\n\n❌ **Avoid GraphQL when:**\n- Simple CRUD operations dominate\n- HTTP caching is critical (GraphQL uses POST)\n- File uploads are primary feature (requires extensions)\n- Team lacks GraphQL expertise\n- Performance optimization is complex (N+1 problem)\n\n**Example Use Cases**: Client-facing APIs, dashboards, mobile apps with varied UIs\n\n### When to Choose gRPC\n\n✅ **Use gRPC when:**\n- Microservice-to-microservice communication\n- High performance and low latency critical\n- Bidirectional streaming needed\n- Strong typing with Protocol Buffers\n- Polyglot environments (language interop)\n\n❌ **Avoid gRPC when:**\n- Browser clients (limited support, needs grpc-web)\n- HTTP\u002FJSON required for compatibility\n- Human-readable payloads preferred\n- Simple request\u002Fresponse patterns\n\n**Example Use Cases**: Internal microservices, streaming data, service mesh\n\n## REST API Patterns\n\n### Resource Naming\n\n✅ **Good: Plural nouns, hierarchical**\n```\nGET    \u002Fusers              # List users\nGET    \u002Fusers\u002F123          # Get user\nPOST   \u002Fusers              # Create user\nPUT    \u002Fusers\u002F123          # Update user (full)\nPATCH  \u002Fusers\u002F123          # Update user (partial)\nDELETE \u002Fusers\u002F123          # Delete user\nGET    \u002Fusers\u002F123\u002Forders   # User's orders (sub-resource)\n```\n\n❌ **Bad: Verbs, mixed conventions**\n```\nGET    \u002FgetUsers           # Don't use verbs\nPOST   \u002Fuser\u002Fcreate        # Don't use verbs\nGET    \u002FUsers\u002F123          # Don't capitalize\nGET    \u002Fuser\u002F123           # Don't mix singular\u002Fplural\n```\n\n### HTTP Status Codes\n\n**Success Codes**:\n- `200 OK`: Successful GET, PUT, PATCH, DELETE with body\n- `201 Created`: Successful POST, return Location header\n- `202 Accepted`: Async operation started\n- `204 No Content`: Successful DELETE, no body\n\n**Client Error Codes**:\n- `400 Bad Request`: Invalid input, validation error\n- `401 Unauthorized`: Missing or invalid authentication\n- `403 Forbidden`: Authenticated but insufficient permissions\n- `404 Not Found`: Resource doesn't exist\n- `409 Conflict`: State conflict (duplicate, version mismatch)\n- `422 Unprocessable Entity`: Semantic validation error\n- `429 Too Many Requests`: Rate limit exceeded\n\n**Server Error Codes**:\n- `500 Internal Server Error`: Unexpected error\n- `502 Bad Gateway`: Upstream service error\n- `503 Service Unavailable`: Temporary outage\n- `504 Gateway Timeout`: Upstream timeout\n\n### Error Response Format\n\n✅ **Consistent error structure**\n```json\n{\n  \"error\": {\n    \"code\": \"VALIDATION_ERROR\",\n    \"message\": \"Invalid request parameters\",\n    \"details\": [\n      {\n        \"field\": \"email\",\n        \"message\": \"Invalid email format\",\n        \"code\": \"INVALID_FORMAT\"\n      }\n    ],\n    \"request_id\": \"req_abc123\",\n    \"documentation_url\": \"https:\u002F\u002Fapi.example.com\u002Fdocs\u002Ferrors\u002Fvalidation\"\n  }\n}\n```\n\n### Pagination Patterns\n\n**Offset Pagination** (simple, familiar):\n```\nGET \u002Fusers?limit=20&offset=40\n```\n✅ Use for: Small datasets, admin interfaces\n❌ Avoid for: Large datasets (skips become expensive), real-time data\n\n**Cursor Pagination** (stable, efficient):\n```\nGET \u002Fusers?limit=20&cursor=eyJpZCI6MTIzfQ\nResponse: { \"data\": [...], \"next_cursor\": \"eyJpZCI6MTQzfQ\" }\n```\n✅ Use for: Infinite scroll, real-time feeds, large datasets\n❌ Avoid for: Random access, page numbers\n\n**Keyset Pagination** (performant):\n```\nGET \u002Fusers?limit=20&after_id=123\n```\n✅ Use for: Ordered data, database index friendly\n❌ Avoid for: Complex sorting, multiple sort keys\n\nSee `references\u002Frest-patterns.md` for filtering, sorting, field selection, HATEOAS\n\n## GraphQL Patterns\n\n### Schema Design\n\n✅ **Good: Clear types, nullable by default**\n```graphql\ntype User {\n  id: ID!                    # Non-null ID\n  email: String!             # Required field\n  name: String               # Optional (nullable by default)\n  createdAt: DateTime!\n  orders: [Order!]!          # Non-null array of non-null orders\n}\n\ntype Query {\n  user(id: ID!): User\n  users(first: Int, after: String): UserConnection!\n}\n\ntype Mutation {\n  createUser(input: CreateUserInput!): CreateUserPayload!\n}\n\ninput CreateUserInput {\n  email: String!\n  name: String\n}\n\ntype CreateUserPayload {\n  user: User\n  userEdge: UserEdge\n  errors: [UserError!]\n}\n```\n\n### Resolver Patterns\n\n**Avoid N+1 Queries with DataLoader**:\n```typescript\nimport DataLoader from 'dataloader';\n\nconst userLoader = new DataLoader(async (userIds: string[]) => {\n  const users = await db.users.findMany({ where: { id: { in: userIds } } });\n  return userIds.map(id => users.find(u => u.id === id));\n});\n\n\u002F\u002F Resolver batches queries automatically\nconst resolvers = {\n  Order: {\n    user: (order) => userLoader.load(order.userId)\n  }\n};\n```\n\n### Query Complexity Analysis\n\nPrevent expensive queries:\n```typescript\nimport { createComplexityLimitRule } from 'graphql-validation-complexity';\n\nconst server = new ApolloServer({\n  schema,\n  validationRules: [\n    createComplexityLimitRule(1000, {\n      onCost: (cost) => console.log('Query cost:', cost),\n    }),\n  ],\n});\n```\n\nSee `references\u002Fgraphql-patterns.md` for subscriptions, relay cursor connections, error handling\n\n## gRPC Patterns\n\n### Service Definition\n\n```protobuf\nsyntax = \"proto3\";\n\npackage users.v1;\n\nservice UserService {\n  rpc GetUser (GetUserRequest) returns (User) {}\n  rpc ListUsers (ListUsersRequest) returns (ListUsersResponse) {}\n  rpc CreateUser (CreateUserRequest) returns (User) {}\n  rpc StreamUsers (StreamUsersRequest) returns (stream User) {}\n  rpc BidiChat (stream ChatMessage) returns (stream ChatMessage) {}\n}\n\nmessage User {\n  string id = 1;\n  string email = 2;\n  string name = 3;\n  google.protobuf.Timestamp created_at = 4;\n}\n\nmessage GetUserRequest {\n  string id = 1;\n}\n\nmessage ListUsersRequest {\n  int32 page_size = 1;\n  string page_token = 2;\n}\n\nmessage ListUsersResponse {\n  repeated User users = 1;\n  string next_page_token = 2;\n}\n```\n\n### Error Handling\n\n```go\nimport (\n    \"google.golang.org\u002Fgrpc\u002Fcodes\"\n    \"google.golang.org\u002Fgrpc\u002Fstatus\"\n)\n\nfunc (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {\n    if req.Id == \"\" {\n        return nil, status.Error(codes.InvalidArgument, \"user ID is required\")\n    }\n\n    user, err := s.db.GetUser(ctx, req.Id)\n    if err != nil {\n        if errors.Is(err, sql.ErrNoRows) {\n            return nil, status.Error(codes.NotFound, \"user not found\")\n        }\n        return nil, status.Error(codes.Internal, \"database error\")\n    }\n\n    return user, nil\n}\n```\n\nSee `references\u002Fgrpc-patterns.md` for streaming, interceptors, metadata, health checks\n\n## Versioning Strategies\n\n### URI Versioning (Simple, Explicit)\n\n✅ **Most common, easy to understand**\n```\nGET \u002Fv1\u002Fusers\u002F123\nGET \u002Fv2\u002Fusers\u002F123\n```\n\n**Pros**: Clear, easy to route, browser-friendly\n**Cons**: Couples version to URL, duplicates routes\n\n### Header Versioning (Clean URLs)\n\n```\nGET \u002Fusers\u002F123\nAccept: application\u002Fvnd.myapi.v2+json\n```\n\n**Pros**: Clean URLs, version separate from resource\n**Cons**: Less visible, harder to test manually\n\n### Content Negotiation (Granular)\n\n```\nGET \u002Fusers\u002F123\nAccept: application\u002Fvnd.myapi.user.v2+json\n```\n\n**Pros**: Resource-level versioning, backward compatible\n**Cons**: Complex, harder to implement\n\n### Version Deprecation Process\n\n```json\n{\n  \"version\": \"1.0\",\n  \"deprecated\": true,\n  \"sunset_date\": \"2025-12-31\",\n  \"migration_guide\": \"https:\u002F\u002Fdocs.api.com\u002Fv1-to-v2\",\n  \"replacement_version\": \"2.0\"\n}\n```\n\n**Include deprecation warnings**:\n```\nHTTP\u002F1.1 200 OK\nDeprecation: true\nSunset: Sat, 31 Dec 2025 23:59:59 GMT\nLink: \u003Chttps:\u002F\u002Fdocs.api.com\u002Fv1-to-v2>; rel=\"deprecation\"\n```\n\nSee `references\u002Fversioning-strategies.md` for detailed migration patterns\n\n## Authentication & Authorization\n\n### OAuth 2.0 (Delegated Access)\n\n**Use for**: Third-party access, user consent, token refresh\n\n**Authorization Code Flow** (most secure for web\u002Fmobile):\n```\n1. Client redirects to \u002Fauthorize\n2. User authenticates, grants permissions\n3. Auth server redirects to callback with code\n4. Client exchanges code for access token\n5. Client uses access token for API requests\n```\n\n```http\n# Request token\nPOST \u002Foauth\u002Ftoken\nContent-Type: application\u002Fx-www-form-urlencoded\n\ngrant_type=authorization_code\n&code=AUTH_CODE\n&redirect_uri=https:\u002F\u002Fclient.com\u002Fcallback\n&client_id=CLIENT_ID\n&client_secret=CLIENT_SECRET\n\n# Response\n{\n  \"access_token\": \"eyJhbGc...\",\n  \"token_type\": \"Bearer\",\n  \"expires_in\": 3600,\n  \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n  \"scope\": \"read write\"\n}\n\n# Use token\nGET \u002Fv1\u002Fusers\u002Fme\nAuthorization: Bearer eyJhbGc...\n```\n\n### JWT (Stateless Auth)\n\n**Use for**: Microservices, stateless API auth, short-lived tokens\n\n✅ **Good: Minimal claims, short expiry**\n```json\n{\n  \"sub\": \"user_123\",\n  \"iat\": 1516239022,\n  \"exp\": 1516242622,\n  \"scope\": \"read:users write:orders\"\n}\n```\n\n**Validation**:\n```typescript\nimport jwt from 'jsonwebtoken';\n\nconst token = req.headers.authorization?.split(' ')[1];\nconst payload = jwt.verify(token, process.env.JWT_SECRET);\nreq.userId = payload.sub;\n```\n\n### API Keys (Service-to-Service)\n\n**Use for**: Server-to-server, CLI tools, webhooks\n\n```http\nGET \u002Fv1\u002Fusers\nX-API-Key: sk_live_abc123...\n\n# Or query parameter (less secure)\nGET \u002Fv1\u002Fusers?api_key=sk_live_abc123\n```\n\n**Key Practices**:\n- Prefix keys with environment (`sk_live_`, `sk_test_`)\n- Hash keys before storage (bcrypt, scrypt)\n- Allow key rotation without downtime\n- Support multiple keys per user\n- Rate limit per key\n\nSee `references\u002Fauthentication.md` for API key rotation, scopes, RBAC\n\n## Rate Limiting\n\n### Token Bucket (Burst-Friendly)\n\n```\nBucket: 100 tokens, refill 10\u002Fsecond\nRequest costs 1 token\nAllows bursts up to bucket size\n```\n\n**Headers**:\n```http\nHTTP\u002F1.1 200 OK\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 73\nX-RateLimit-Reset: 1640995200\n```\n\n**429 Response**:\n```http\nHTTP\u002F1.1 429 Too Many Requests\nRetry-After: 60\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 0\nX-RateLimit-Reset: 1640995200\n\n{\n  \"error\": {\n    \"code\": \"RATE_LIMIT_EXCEEDED\",\n    \"message\": \"Rate limit exceeded. Try again in 60 seconds.\",\n    \"limit\": 100,\n    \"reset_at\": \"2025-01-01T00:00:00Z\"\n  }\n}\n```\n\n### Sliding Window (Fair Distribution)\n\nCounts requests in rolling time window. More accurate than fixed window.\n\n### Per-User vs Per-IP\n\n- **Per-User**: Authenticated requests, fair quotas\n- **Per-IP**: Unauthenticated requests, prevent abuse\n- **Combined**: Both limits, take stricter\n\n## Idempotency\n\n### Idempotent Methods (HTTP Spec)\n\n**Naturally Idempotent**: GET, PUT, DELETE, HEAD, OPTIONS\n**Not Idempotent**: POST, PATCH\n\n### Idempotency Keys\n\nMake POST requests idempotent:\n```http\nPOST \u002Fv1\u002Fpayments\nIdempotency-Key: uuid-or-client-generated-key\nContent-Type: application\u002Fjson\n\n{\n  \"amount\": 1000,\n  \"currency\": \"USD\",\n  \"customer\": \"cust_123\"\n}\n```\n\n**Server behavior**:\n1. First request: Process and store result with key\n2. Duplicate request (same key): Return stored result (200 or 201)\n3. Different request (same key): Return 409 Conflict\n\n**Implementation**:\n```typescript\nconst idempotencyKey = req.headers['idempotency-key'];\nif (idempotencyKey) {\n  const cached = await redis.get(`idempotency:${idempotencyKey}`);\n  if (cached) {\n    return res.status(cached.status).json(cached.body);\n  }\n}\n\nconst result = await processPayment(req.body);\nawait redis.setex(`idempotency:${idempotencyKey}`, 86400, {\n  status: 201,\n  body: result\n});\n```\n\n### Conditional Requests\n\nUse ETags for safe updates:\n```http\n# Get resource with ETag\nGET \u002Fv1\u002Fusers\u002F123\nResponse: ETag: \"abc123\"\n\n# Update only if unchanged\nPUT \u002Fv1\u002Fusers\u002F123\nIf-Match: \"abc123\"\n\n# 412 Precondition Failed if ETag changed\n```\n\n## Caching Strategies\n\n### HTTP Caching Headers\n\n```http\n# Public, cacheable for 1 hour\nCache-Control: public, max-age=3600\n\n# Private (user-specific), revalidate\nCache-Control: private, must-revalidate, max-age=0\n\n# No caching\nCache-Control: no-store, no-cache, must-revalidate\n```\n\n### ETag Validation\n\n```http\n# Server returns ETag\nGET \u002Fv1\u002Fusers\u002F123\nResponse:\n  ETag: \"33a64df551425fcc55e4d42a148795d9f25f89d4\"\n  Cache-Control: max-age=3600\n\n# Client conditional request\nGET \u002Fv1\u002Fusers\u002F123\nIf-None-Match: \"33a64df551425fcc55e4d42a148795d9f25f89d4\"\n\n# 304 Not Modified if unchanged (saves bandwidth)\nHTTP\u002F1.1 304 Not Modified\n```\n\n### Last-Modified\n\n```http\nGET \u002Fv1\u002Fusers\u002F123\nResponse:\n  Last-Modified: Wed, 21 Oct 2025 07:28:00 GMT\n\n# Conditional request\nGET \u002Fv1\u002Fusers\u002F123\nIf-Modified-Since: Wed, 21 Oct 2025 07:28:00 GMT\n\n# 304 Not Modified if not modified\n```\n\n## Webhooks\n\n### Event Delivery\n\n```http\nPOST https:\u002F\u002Fclient.com\u002Fwebhooks\u002Fpayments\nContent-Type: application\u002Fjson\nX-Webhook-Signature: sha256=abc123...\nX-Webhook-Id: evt_abc123\nX-Webhook-Timestamp: 1640995200\n\n{\n  \"id\": \"evt_abc123\",\n  \"type\": \"payment.succeeded\",\n  \"created\": 1640995200,\n  \"data\": {\n    \"object\": {\n      \"id\": \"pay_123\",\n      \"amount\": 1000,\n      \"status\": \"succeeded\"\n    }\n  }\n}\n```\n\n### Signature Verification\n\n```typescript\nimport crypto from 'crypto';\n\nfunction verifyWebhookSignature(\n  payload: string,\n  signature: string,\n  secret: string\n): boolean {\n  const expectedSignature = crypto\n    .createHmac('sha256', secret)\n    .update(payload)\n    .digest('hex');\n  return crypto.timingSafeEqual(\n    Buffer.from(signature),\n    Buffer.from(`sha256=${expectedSignature}`)\n  );\n}\n```\n\n### Retry Strategy\n\n- **Exponential backoff**: 1s, 2s, 4s, 8s, 16s, 32s, 64s\n- **Timeout**: 5-30 seconds per attempt\n- **Max attempts**: 3-7 attempts\n- **Dead letter queue**: Store failed events\n- **Manual retry**: UI for re-sending failed events\n\n## API Documentation\n\n### OpenAPI\u002FSwagger (REST)\n\n```yaml\nopenapi: 3.0.0\ninfo:\n  title: User API\n  version: 1.0.0\npaths:\n  \u002Fusers\u002F{id}:\n    get:\n      summary: Get user by ID\n      parameters:\n        - name: id\n          in: path\n          required: true\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Successful response\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: '#\u002Fcomponents\u002Fschemas\u002FUser'\n        '404':\n          description: User not found\ncomponents:\n  schemas:\n    User:\n      type: object\n      required: [id, email]\n      properties:\n        id:\n          type: string\n        email:\n          type: string\n          format: email\n        name:\n          type: string\n```\n\n### GraphQL Schema (Self-Documenting)\n\nGraphQL introspection provides automatic documentation. Use descriptions:\n\n```graphql\n\"\"\"\nRepresents a user account in the system.\nCreated via the createUser mutation.\n\"\"\"\ntype User {\n  \"\"\"Unique identifier for the user\"\"\"\n  id: ID!\n\n  \"\"\"Email address, must be unique\"\"\"\n  email: String!\n\n  \"\"\"Optional display name\"\"\"\n  name: String\n}\n```\n\n### API Documentation Best Practices\n\n1. **Interactive examples**: Provide working code samples\n2. **Authentication guide**: Step-by-step auth setup\n3. **Error catalog**: Document all error codes with examples\n4. **Rate limits**: Clearly state limits and headers\n5. **Changelog**: Track breaking and non-breaking changes\n6. **Migration guides**: Version upgrade instructions\n7. **SDKs**: Provide client libraries for popular languages\n\n## Anti-Patterns\n\n❌ **Over-fetching (REST)**: Returning entire objects when fields are unused\n✅ **Solution**: Support field selection (`?fields=id,name,email`)\n\n❌ **Under-fetching (REST)**: Requiring multiple requests for related data\n✅ **Solution**: Support expansion (`?expand=orders,profile`) or use GraphQL\n\n❌ **Chatty APIs**: Too many round-trips for common operations\n✅ **Solution**: Batch endpoints, compound documents, or GraphQL\n\n❌ **Ignoring HTTP semantics**: Using GET for mutations, wrong status codes\n✅ **Solution**: Follow HTTP spec, use correct methods and status codes\n\n❌ **Exposing internal structure**: URLs\u002Fschemas mirror database\n✅ **Solution**: Design resource-oriented APIs independent of storage\n\n❌ **Missing versioning**: Breaking changes without version increments\n✅ **Solution**: Version from day one, never break existing versions\n\n❌ **Poor error messages**: Generic \"An error occurred\"\n✅ **Solution**: Specific, actionable error messages with codes\n\n❌ **No rate limiting**: APIs vulnerable to abuse\n✅ **Solution**: Implement rate limiting from the start\n\n## Testing Strategies\n\n### Contract Testing\n\n```typescript\n\u002F\u002F Pact contract test\nimport { PactV3 } from '@pact-foundation\u002Fpact';\n\nconst provider = new PactV3({\n  consumer: 'FrontendApp',\n  provider: 'UserAPI'\n});\n\nit('gets a user by ID', () => {\n  provider\n    .given('user 123 exists')\n    .uponReceiving('a request for user 123')\n    .withRequest({\n      method: 'GET',\n      path: '\u002Fusers\u002F123'\n    })\n    .willRespondWith({\n      status: 200,\n      body: { id: '123', email: 'user@example.com' }\n    });\n});\n```\n\n### Load Testing\n\n```javascript\n\u002F\u002F k6 load test\nimport http from 'k6\u002Fhttp';\nimport { check } from 'k6';\n\nexport const options = {\n  stages: [\n    { duration: '30s', target: 20 },\n    { duration: '1m', target: 20 },\n    { duration: '10s', target: 0 }\n  ],\n  thresholds: {\n    http_req_duration: ['p(95)\u003C500'], \u002F\u002F 95% under 500ms\n    http_req_failed: ['rate\u003C0.01']    \u002F\u002F \u003C1% errors\n  }\n};\n\nexport default function () {\n  const res = http.get('https:\u002F\u002Fapi.example.com\u002Fusers');\n  check(res, {\n    'status is 200': (r) => r.status === 200,\n    'response time \u003C 500ms': (r) => r.timings.duration \u003C 500\n  });\n}\n```\n\n## Related Skills\n\n- **graphql**: Deep GraphQL schema design, resolvers, Apollo Server\n- **typescript**: Type-safe API clients and servers\n- **nodejs-backend**: Express\u002FFastify REST API implementation\n- **django**: Django REST Framework patterns\n- **fastapi**: FastAPI Python REST\u002FGraphQL APIs\n- **flask**: Flask-RESTful patterns\n\n## References\n\n- **rest-patterns.md**: Deep REST coverage (HATEOAS, filtering, field selection)\n- **graphql-patterns.md**: GraphQL subscriptions, relay cursor connections, federation\n- **grpc-patterns.md**: Streaming patterns, interceptors, service mesh integration\n- **versioning-strategies.md**: Detailed versioning approaches and migration patterns\n- **authentication.md**: OAuth flows, JWT best practices, API key rotation, RBAC\n\n## Additional Resources\n\n- [REST API Design Rulebook](https:\u002F\u002Fwww.oreilly.com\u002Flibrary\u002Fview\u002Frest-api-design\u002F9781449317904\u002F) - O'Reilly REST guide\n- [GraphQL Best Practices](https:\u002F\u002Fgraphql.org\u002Flearn\u002Fbest-practices\u002F) - Official GraphQL guide\n- [gRPC Best Practices](https:\u002F\u002Fgrpc.io\u002Fdocs\u002Fguides\u002Fperformance\u002F) - Official gRPC guide\n- [RFC 7807: Problem Details for HTTP APIs](https:\u002F\u002Ftools.ietf.org\u002Fhtml\u002Frfc7807) - Standard error format\n- [OpenAPI Specification](https:\u002F\u002Fspec.openapis.org\u002Foas\u002Flatest.html) - REST documentation standard\n","# API Design Patterns\n\nDesign robust, scalable APIs using proven patterns for REST, GraphQL, and gRPC with proper versioning, authentication, and error handling.\n\n## Quick Reference\n\n**API Style Selection**:\n- REST: Resource-based CRUD, simple clients, HTTP-native caching\n- GraphQL: Client-driven queries, complex data graphs, real-time subscriptions\n- gRPC: High-performance RPC, microservices, strong typing, streaming\n\n**Critical Patterns**:\n- Versioning: URI (`\u002Fv1\u002Fusers`), header (`Accept: application\u002Fvnd.api+json;version=1`), content negotiation\n- Pagination: Offset (simple), cursor (stable), keyset (performant)\n- Auth: OAuth2 (delegated), JWT (stateless), API keys (service-to-service)\n- Rate limiting: Token bucket, fixed window, sliding window\n- Idempotency: Idempotency keys, conditional requests, safe retry\n\n**See references\u002F for deep dives**: `rest-patterns.md`, `graphql-patterns.md`, `grpc-patterns.md`, `versioning-strategies.md`, `authentication.md`\n\n## Core Principles\n\n### Universal API Design Standards\n\nApply these principles across all API styles:\n\n**1. Consistency Over Cleverness**\n- Follow established conventions for your API style\n- Use predictable naming patterns (snake_case or camelCase, pick one)\n- Maintain consistent error response formats\n- Version breaking changes, never surprise clients\n\n**2. Design for Evolution**\n- Plan for versioning from day one\n- Use optional fields with sensible defaults\n- Deprecate gracefully with sunset dates\n- Document breaking vs non-breaking changes\n\n**3. Security by Default**\n- Require authentication unless explicitly public\n- Use HTTPS\u002FTLS for all production endpoints\n- Implement rate limiting and throttling\n- Validate and sanitize all inputs\n- Return minimal error details to clients\n\n**4. Developer Experience First**\n- Provide comprehensive documentation (OpenAPI, GraphQL schema)\n- Return meaningful error messages with actionable guidance\n- Use standard HTTP status codes correctly\n- Include request IDs for debugging\n- Offer SDKs and code generators\n\n## API Style Decision Tree\n\n### When to Choose REST\n\n✅ **Use REST when:**\n- Building CRUD-focused resource APIs\n- Clients need HTTP caching (ETags, Cache-Control)\n- Wide platform compatibility required (browsers, mobile, IoT)\n- Simple, stateless client-server model fits\n- Team familiar with HTTP\u002FREST conventions\n\n❌ **Avoid REST when:**\n- Complex data fetching with nested relationships (N+1 queries)\n- Real-time updates are primary use case\n- Need strong typing and code generation\n- High-performance RPC between microservices\n\n**Example Use Cases**: Public APIs, mobile backends, traditional web services\n\n### When to Choose GraphQL\n\n✅ **Use GraphQL when:**\n- Clients need flexible, client-driven queries\n- Complex data graphs with nested relationships\n- Multiple client types with different data needs\n- Real-time subscriptions required\n- Strong typing and schema validation needed\n\n❌ **Avoid GraphQL when:**\n- Simple CRUD operations dominate\n- HTTP caching is critical (GraphQL uses POST)\n- File uploads are primary feature (requires extensions)\n- Team lacks GraphQL expertise\n- Performance optimization is complex (N+1 problem)\n\n**Example Use Cases**: Client-facing APIs, dashboards, mobile apps with varied UIs\n\n### When to Choose gRPC\n\n✅ **Use gRPC when:**\n- Microservice-to-microservice communication\n- High performance and low latency critical\n- Bidirectional streaming needed\n- Strong typing with Protocol Buffers\n- Polyglot environments (language interop)\n\n❌ **Avoid gRPC when:**\n- Browser clients (limited support, needs grpc-web)\n- HTTP\u002FJSON required for compatibility\n- Human-readable payloads preferred\n- Simple request\u002Fresponse patterns\n\n**Example Use Cases**: Internal microservices, streaming data, service mesh\n\n## REST API Patterns\n\n### Resource Naming\n\n✅ **Good: Plural nouns, hierarchical**\n```\nGET    \u002Fusers              # List users\nGET    \u002Fusers\u002F123          # Get user\nPOST   \u002Fusers              # Create user\nPUT    \u002Fusers\u002F123          # Update user (full)\nPATCH  \u002Fusers\u002F123          # Update user (partial)\nDELETE \u002Fusers\u002F123          # Delete user\nGET    \u002Fusers\u002F123\u002Forders   # User's orders (sub-resource)\n```\n\n❌ **Bad: Verbs, mixed conventions**\n```\nGET    \u002FgetUsers           # Don't use verbs\nPOST   \u002Fuser\u002Fcreate        # Don't use verbs\nGET    \u002FUsers\u002F123          # Don't capitalize\nGET    \u002Fuser\u002F123           # Don't mix singular\u002Fplural\n```\n\n### HTTP Status Codes\n\n**Success Codes**:\n- `200 OK`: Successful GET, PUT, PATCH, DELETE with body\n- `201 Created`: Successful POST, return Location header\n- `202 Accepted`: Async operation started\n- `204 No Content`: Successful DELETE, no body\n\n**Client Error Codes**:\n- `400 Bad Request`: Invalid input, validation error\n- `401 Unauthorized`: Missing or invalid authentication\n- `403 Forbidden`: Authenticated but insufficient permissions\n- `404 Not Found`: Resource doesn't exist\n- `409 Conflict`: State conflict (duplicate, version mismatch)\n- `422 Unprocessable Entity`: Semantic validation error\n- `429 Too Many Requests`: Rate limit exceeded\n\n**Server Error Codes**:\n- `500 Internal Server Error`: Unexpected error\n- `502 Bad Gateway`: Upstream service error\n- `503 Service Unavailable`: Temporary outage\n- `504 Gateway Timeout`: Upstream timeout\n\n### Error Response Format\n\n✅ **Consistent error structure**\n```json\n{\n  \"error\": {\n    \"code\": \"VALIDATION_ERROR\",\n    \"message\": \"Invalid request parameters\",\n    \"details\": [\n      {\n        \"field\": \"email\",\n        \"message\": \"Invalid email format\",\n        \"code\": \"INVALID_FORMAT\"\n      }\n    ],\n    \"request_id\": \"req_abc123\",\n    \"documentation_url\": \"https:\u002F\u002Fapi.example.com\u002Fdocs\u002Ferrors\u002Fvalidation\"\n  }\n}\n```\n\n### Pagination Patterns\n\n**Offset Pagination** (simple, familiar):\n```\nGET \u002Fusers?limit=20&offset=40\n```\n✅ Use for: Small datasets, admin interfaces\n❌ Avoid for: Large datasets (skips become expensive), real-time data\n\n**Cursor Pagination** (stable, efficient):\n```\nGET \u002Fusers?limit=20&cursor=eyJpZCI6MTIzfQ\nResponse: { \"data\": [...], \"next_cursor\": \"eyJpZCI6MTQzfQ\" }\n```\n✅ Use for: Infinite scroll, real-time feeds, large datasets\n❌ Avoid for: Random access, page numbers\n\n**Keyset Pagination** (performant):\n```\nGET \u002Fusers?limit=20&after_id=123\n```\n✅ Use for: Ordered data, database index friendly\n❌ Avoid for: Complex sorting, multiple sort keys\n\nSee `references\u002Frest-patterns.md` for filtering, sorting, field selection, HATEOAS\n\n## GraphQL Patterns\n\n### Schema Design\n\n✅ **Good: Clear types, nullable by default**\n```graphql\ntype User {\n  id: ID!                    # Non-null ID\n  email: String!             # Required field\n  name: String               # Optional (nullable by default)\n  createdAt: DateTime!\n  orders: [Order!]!          # Non-null array of non-null orders\n}\n\ntype Query {\n  user(id: ID!): User\n  users(first: Int, after: String): UserConnection!\n}\n\ntype Mutation {\n  createUser(input: CreateUserInput!): CreateUserPayload!\n}\n\ninput CreateUserInput {\n  email: String!\n  name: String\n}\n\ntype CreateUserPayload {\n  user: User\n  userEdge: UserEdge\n  errors: [UserError!]\n}\n```\n\n### Resolver Patterns\n\n**Avoid N+1 Queries with DataLoader**:\n```typescript\nimport DataLoader from 'dataloader';\n\nconst userLoader = new DataLoader(async (userIds: string[]) => {\n  const users = await db.users.findMany({ where: { id: { in: userIds } } });\n  return userIds.map(id => users.find(u => u.id === id));\n});\n\n\u002F\u002F Resolver batches queries automatically\nconst resolvers = {\n  Order: {\n    user: (order) => userLoader.load(order.userId)\n  }\n};\n```\n\n### Query Complexity Analysis\n\nPrevent expensive queries:\n```typescript\nimport { createComplexityLimitRule } from 'graphql-validation-complexity';\n\nconst server = new ApolloServer({\n  schema,\n  validationRules: [\n    createComplexityLimitRule(1000, {\n      onCost: (cost) => console.log('Query cost:', cost),\n    }),\n  ],\n});\n```\n\nSee `references\u002Fgraphql-patterns.md` for subscriptions, relay cursor connections, error handling\n\n## gRPC Patterns\n\n### Service Definition\n\n```protobuf\nsyntax = \"proto3\";\n\npackage users.v1;\n\nservice UserService {\n  rpc GetUser (GetUserRequest) returns (User) {}\n  rpc ListUsers (ListUsersRequest) returns (ListUsersResponse) {}\n  rpc CreateUser (CreateUserRequest) returns (User) {}\n  rpc StreamUsers (StreamUsersRequest) returns (stream User) {}\n  rpc BidiChat (stream ChatMessage) returns (stream ChatMessage) {}\n}\n\nmessage User {\n  string id = 1;\n  string email = 2;\n  string name = 3;\n  google.protobuf.Timestamp created_at = 4;\n}\n\nmessage GetUserRequest {\n  string id = 1;\n}\n\nmessage ListUsersRequest {\n  int32 page_size = 1;\n  string page_token = 2;\n}\n\nmessage ListUsersResponse {\n  repeated User users = 1;\n  string next_page_token = 2;\n}\n```\n\n### Error Handling\n\n```go\nimport (\n    \"google.golang.org\u002Fgrpc\u002Fcodes\"\n    \"google.golang.org\u002Fgrpc\u002Fstatus\"\n)\n\nfunc (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {\n    if req.Id == \"\" {\n        return nil, status.Error(codes.InvalidArgument, \"user ID is required\")\n    }\n\n    user, err := s.db.GetUser(ctx, req.Id)\n    if err != nil {\n        if errors.Is(err, sql.ErrNoRows) {\n            return nil, status.Error(codes.NotFound, \"user not found\")\n        }\n        return nil, status.Error(codes.Internal, \"database error\")\n    }\n\n    return user, nil\n}\n```\n\nSee `references\u002Fgrpc-patterns.md` for streaming, interceptors, metadata, health checks\n\n## Versioning Strategies\n\n### URI Versioning (Simple, Explicit)\n\n✅ **Most common, easy to understand**\n```\nGET \u002Fv1\u002Fusers\u002F123\nGET \u002Fv2\u002Fusers\u002F123\n```\n\n**Pros**: Clear, easy to route, browser-friendly\n**Cons**: Couples version to URL, duplicates routes\n\n### Header Versioning (Clean URLs)\n\n```\nGET \u002Fusers\u002F123\nAccept: application\u002Fvnd.myapi.v2+json\n```\n\n**Pros**: Clean URLs, version separate from resource\n**Cons**: Less visible, harder to test manually\n\n### Content Negotiation (Granular)\n\n```\nGET \u002Fusers\u002F123\nAccept: application\u002Fvnd.myapi.user.v2+json\n```\n\n**Pros**: Resource-level versioning, backward compatible\n**Cons**: Complex, harder to implement\n\n### Version Deprecation Process\n\n```json\n{\n  \"version\": \"1.0\",\n  \"deprecated\": true,\n  \"sunset_date\": \"2025-12-31\",\n  \"migration_guide\": \"https:\u002F\u002Fdocs.api.com\u002Fv1-to-v2\",\n  \"replacement_version\": \"2.0\"\n}\n```\n\n**Include deprecation warnings**:\n```\nHTTP\u002F1.1 200 OK\nDeprecation: true\nSunset: Sat, 31 Dec 2025 23:59:59 GMT\nLink: \u003Chttps:\u002F\u002Fdocs.api.com\u002Fv1-to-v2>; rel=\"deprecation\"\n```\n\nSee `references\u002Fversioning-strategies.md` for detailed migration patterns\n\n## Authentication & Authorization\n\n### OAuth 2.0 (Delegated Access)\n\n**Use for**: Third-party access, user consent, token refresh\n\n**Authorization Code Flow** (most secure for web\u002Fmobile):\n```\n1. Client redirects to \u002Fauthorize\n2. User authenticates, grants permissions\n3. Auth server redirects to callback with code\n4. Client exchanges code for access token\n5. Client uses access token for API requests\n```\n\n```http\n# Request token\nPOST \u002Foauth\u002Ftoken\nContent-Type: application\u002Fx-www-form-urlencoded\n\ngrant_type=authorization_code\n&code=AUTH_CODE\n&redirect_uri=https:\u002F\u002Fclient.com\u002Fcallback\n&client_id=CLIENT_ID\n&client_secret=CLIENT_SECRET\n\n# Response\n{\n  \"access_token\": \"eyJhbGc...\",\n  \"token_type\": \"Bearer\",\n  \"expires_in\": 3600,\n  \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n  \"scope\": \"read write\"\n}\n\n# Use token\nGET \u002Fv1\u002Fusers\u002Fme\nAuthorization: Bearer eyJhbGc...\n```\n\n### JWT (Stateless Auth)\n\n**Use for**: Microservices, stateless API auth, short-lived tokens\n\n✅ **Good: Minimal claims, short expiry**\n```json\n{\n  \"sub\": \"user_123\",\n  \"iat\": 1516239022,\n  \"exp\": 1516242622,\n  \"scope\": \"read:users write:orders\"\n}\n```\n\n**Validation**:\n```typescript\nimport jwt from 'jsonwebtoken';\n\nconst token = req.headers.authorization?.split(' ')[1];\nconst payload = jwt.verify(token, process.env.JWT_SECRET);\nreq.userId = payload.sub;\n```\n\n### API Keys (Service-to-Service)\n\n**Use for**: Server-to-server, CLI tools, webhooks\n\n```http\nGET \u002Fv1\u002Fusers\nX-API-Key: sk_live_abc123...\n\n# Or query parameter (less secure)\nGET \u002Fv1\u002Fusers?api_key=sk_live_abc123\n```\n\n**Key Practices**:\n- Prefix keys with environment (`sk_live_`, `sk_test_`)\n- Hash keys before storage (bcrypt, scrypt)\n- Allow key rotation without downtime\n- Support multiple keys per user\n- Rate limit per key\n\nSee `references\u002Fauthentication.md` for API key rotation, scopes, RBAC\n\n## Rate Limiting\n\n### Token Bucket (Burst-Friendly)\n\n```\nBucket: 100 tokens, refill 10\u002Fsecond\nRequest costs 1 token\nAllows bursts up to bucket size\n```\n\n**Headers**:\n```http\nHTTP\u002F1.1 200 OK\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 73\nX-RateLimit-Reset: 1640995200\n```\n\n**429 Response**:\n```http\nHTTP\u002F1.1 429 Too Many Requests\nRetry-After: 60\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 0\nX-RateLimit-Reset: 1640995200\n\n{\n  \"error\": {\n    \"code\": \"RATE_LIMIT_EXCEEDED\",\n    \"message\": \"Rate limit exceeded. Try again in 60 seconds.\",\n    \"limit\": 100,\n    \"reset_at\": \"2025-01-01T00:00:00Z\"\n  }\n}\n```\n\n### Sliding Window (Fair Distribution)\n\nCounts requests in rolling time window. More accurate than fixed window.\n\n### Per-User vs Per-IP\n\n- **Per-User**: Authenticated requests, fair quotas\n- **Per-IP**: Unauthenticated requests, prevent abuse\n- **Combined**: Both limits, take stricter\n\n## Idempotency\n\n### Idempotent Methods (HTTP Spec)\n\n**Naturally Idempotent**: GET, PUT, DELETE, HEAD, OPTIONS\n**Not Idempotent**: POST, PATCH\n\n### Idempotency Keys\n\nMake POST requests idempotent:\n```http\nPOST \u002Fv1\u002Fpayments\nIdempotency-Key: uuid-or-client-generated-key\nContent-Type: application\u002Fjson\n\n{\n  \"amount\": 1000,\n  \"currency\": \"USD\",\n  \"customer\": \"cust_123\"\n}\n```\n\n**Server behavior**:\n1. First request: Process and store result with key\n2. Duplicate request (same key): Return stored result (200 or 201)\n3. Different request (same key): Return 409 Conflict\n\n**Implementation**:\n```typescript\nconst idempotencyKey = req.headers['idempotency-key'];\nif (idempotencyKey) {\n  const cached = await redis.get(`idempotency:${idempotencyKey}`);\n  if (cached) {\n    return res.status(cached.status).json(cached.body);\n  }\n}\n\nconst result = await processPayment(req.body);\nawait redis.setex(`idempotency:${idempotencyKey}`, 86400, {\n  status: 201,\n  body: result\n});\n```\n\n### Conditional Requests\n\nUse ETags for safe updates:\n```http\n# Get resource with ETag\nGET \u002Fv1\u002Fusers\u002F123\nResponse: ETag: \"abc123\"\n\n# Update only if unchanged\nPUT \u002Fv1\u002Fusers\u002F123\nIf-Match: \"abc123\"\n\n# 412 Precondition Failed if ETag changed\n```\n\n## Caching Strategies\n\n### HTTP Caching Headers\n\n```http\n# Public, cacheable for 1 hour\nCache-Control: public, max-age=3600\n\n# Private (user-specific), revalidate\nCache-Control: private, must-revalidate, max-age=0\n\n# No caching\nCache-Control: no-store, no-cache, must-revalidate\n```\n\n### ETag Validation\n\n```http\n# Server returns ETag\nGET \u002Fv1\u002Fusers\u002F123\nResponse:\n  ETag: \"33a64df551425fcc55e4d42a148795d9f25f89d4\"\n  Cache-Control: max-age=3600\n\n# Client conditional request\nGET \u002Fv1\u002Fusers\u002F123\nIf-None-Match: \"33a64df551425fcc55e4d42a148795d9f25f89d4\"\n\n# 304 Not Modified if unchanged (saves bandwidth)\nHTTP\u002F1.1 304 Not Modified\n```\n\n### Last-Modified\n\n```http\nGET \u002Fv1\u002Fusers\u002F123\nResponse:\n  Last-Modified: Wed, 21 Oct 2025 07:28:00 GMT\n\n# Conditional request\nGET \u002Fv1\u002Fusers\u002F123\nIf-Modified-Since: Wed, 21 Oct 2025 07:28:00 GMT\n\n# 304 Not Modified if not modified\n```\n\n## Webhooks\n\n### Event Delivery\n\n```http\nPOST https:\u002F\u002Fclient.com\u002Fwebhooks\u002Fpayments\nContent-Type: application\u002Fjson\nX-Webhook-Signature: sha256=abc123...\nX-Webhook-Id: evt_abc123\nX-Webhook-Timestamp: 1640995200\n\n{\n  \"id\": \"evt_abc123\",\n  \"type\": \"payment.succeeded\",\n  \"created\": 1640995200,\n  \"data\": {\n    \"object\": {\n      \"id\": \"pay_123\",\n      \"amount\": 1000,\n      \"status\": \"succeeded\"\n    }\n  }\n}\n```\n\n### Signature Verification\n\n```typescript\nimport crypto from 'crypto';\n\nfunction verifyWebhookSignature(\n  payload: string,\n  signature: string,\n  secret: string\n): boolean {\n  const expectedSignature = crypto\n    .createHmac('sha256', secret)\n    .update(payload)\n    .digest('hex');\n  return crypto.timingSafeEqual(\n    Buffer.from(signature),\n    Buffer.from(`sha256=${expectedSignature}`)\n  );\n}\n```\n\n### Retry Strategy\n\n- **Exponential backoff**: 1s, 2s, 4s, 8s, 16s, 32s, 64s\n- **Timeout**: 5-30 seconds per attempt\n- **Max attempts**: 3-7 attempts\n- **Dead letter queue**: Store failed events\n- **Manual retry**: UI for re-sending failed events\n\n## API Documentation\n\n### OpenAPI\u002FSwagger (REST)\n\n```yaml\nopenapi: 3.0.0\ninfo:\n  title: User API\n  version: 1.0.0\npaths:\n  \u002Fusers\u002F{id}:\n    get:\n      summary: Get user by ID\n      parameters:\n        - name: id\n          in: path\n          required: true\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Successful response\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: '#\u002Fcomponents\u002Fschemas\u002FUser'\n        '404':\n          description: User not found\ncomponents:\n  schemas:\n    User:\n      type: object\n      required: [id, email]\n      properties:\n        id:\n          type: string\n        email:\n          type: string\n          format: email\n        name:\n          type: string\n```\n\n### GraphQL Schema (Self-Documenting)\n\nGraphQL introspection provides automatic documentation. Use descriptions:\n\n```graphql\n\"\"\"\nRepresents a user account in the system.\nCreated via the createUser mutation.\n\"\"\"\ntype User {\n  \"\"\"Unique identifier for the user\"\"\"\n  id: ID!\n\n  \"\"\"Email address, must be unique\"\"\"\n  email: String!\n\n  \"\"\"Optional display name\"\"\"\n  name: String\n}\n```\n\n### API Documentation Best Practices\n\n1. **Interactive examples**: Provide working code samples\n2. **Authentication guide**: Step-by-step auth setup\n3. **Error catalog**: Document all error codes with examples\n4. **Rate limits**: Clearly state limits and headers\n5. **Changelog**: Track breaking and non-breaking changes\n6. **Migration guides**: Version upgrade instructions\n7. **SDKs**: Provide client libraries for popular languages\n\n## Anti-Patterns\n\n❌ **Over-fetching (REST)**: Returning entire objects when fields are unused\n✅ **Solution**: Support field selection (`?fields=id,name,email`)\n\n❌ **Under-fetching (REST)**: Requiring multiple requests for related data\n✅ **Solution**: Support expansion (`?expand=orders,profile`) or use GraphQL\n\n❌ **Chatty APIs**: Too many round-trips for common operations\n✅ **Solution**: Batch endpoints, compound documents, or GraphQL\n\n❌ **Ignoring HTTP semantics**: Using GET for mutations, wrong status codes\n✅ **Solution**: Follow HTTP spec, use correct methods and status codes\n\n❌ **Exposing internal structure**: URLs\u002Fschemas mirror database\n✅ **Solution**: Design resource-oriented APIs independent of storage\n\n❌ **Missing versioning**: Breaking changes without version increments\n✅ **Solution**: Version from day one, never break existing versions\n\n❌ **Poor error messages**: Generic \"An error occurred\"\n✅ **Solution**: Specific, actionable error messages with codes\n\n❌ **No rate limiting**: APIs vulnerable to abuse\n✅ **Solution**: Implement rate limiting from the start\n\n## Testing Strategies\n\n### Contract Testing\n\n```typescript\n\u002F\u002F Pact contract test\nimport { PactV3 } from '@pact-foundation\u002Fpact';\n\nconst provider = new PactV3({\n  consumer: 'FrontendApp',\n  provider: 'UserAPI'\n});\n\nit('gets a user by ID', () => {\n  provider\n    .given('user 123 exists')\n    .uponReceiving('a request for user 123')\n    .withRequest({\n      method: 'GET',\n      path: '\u002Fusers\u002F123'\n    })\n    .willRespondWith({\n      status: 200,\n      body: { id: '123', email: 'user@example.com' }\n    });\n});\n```\n\n### Load Testing\n\n```javascript\n\u002F\u002F k6 load test\nimport http from 'k6\u002Fhttp';\nimport { check } from 'k6';\n\nexport const options = {\n  stages: [\n    { duration: '30s', target: 20 },\n    { duration: '1m', target: 20 },\n    { duration: '10s', target: 0 }\n  ],\n  thresholds: {\n    http_req_duration: ['p(95)\u003C500'], \u002F\u002F 95% under 500ms\n    http_req_failed: ['rate\u003C0.01']    \u002F\u002F \u003C1% errors\n  }\n};\n\nexport default function () {\n  const res = http.get('https:\u002F\u002Fapi.example.com\u002Fusers');\n  check(res, {\n    'status is 200': (r) => r.status === 200,\n    'response time \u003C 500ms': (r) => r.timings.duration \u003C 500\n  });\n}\n```\n\n## Related Skills\n\n- **graphql**: Deep GraphQL schema design, resolvers, Apollo Server\n- **typescript**: Type-safe API clients and servers\n- **nodejs-backend**: Express\u002FFastify REST API implementation\n- **django**: Django REST Framework patterns\n- **fastapi**: FastAPI Python REST\u002FGraphQL APIs\n- **flask**: Flask-RESTful patterns\n\n## References\n\n- **rest-patterns.md**: Deep REST coverage (HATEOAS, filtering, field selection)\n- **graphql-patterns.md**: GraphQL subscriptions, relay cursor connections, federation\n- **grpc-patterns.md**: Streaming patterns, interceptors, service mesh integration\n- **versioning-strategies.md**: Detailed versioning approaches and migration patterns\n- **authentication.md**: OAuth flows, JWT best practices, API key rotation, RBAC\n\n## Additional Resources\n\n- [REST API Design Rulebook](https:\u002F\u002Fwww.oreilly.com\u002Flibrary\u002Fview\u002Frest-api-design\u002F9781449317904\u002F) - O'Reilly REST guide\n- [GraphQL Best Practices](https:\u002F\u002Fgraphql.org\u002Flearn\u002Fbest-practices\u002F) - Official GraphQL guide\n- [gRPC Best Practices](https:\u002F\u002Fgrpc.io\u002Fdocs\u002Fguides\u002Fperformance\u002F) - Official gRPC guide\n- [RFC 7807: Problem Details for HTTP APIs](https:\u002F\u002Ftools.ietf.org\u002Fhtml\u002Frfc7807) - Standard error format\n- [OpenAPI Specification](https:\u002F\u002Fspec.openapis.org\u002Foas\u002Flatest.html) - REST documentation standard\n",{"name":5,"tags":24,"license":15,"metadata":32,"description":7,"compatibility":45,"progressive_disclosure":46},[25,26,27,28,29,30,31],"api","rest","graphql","grpc","architecture","web","design-patterns",{"version":33,"category":34,"token_budget":35,"related_skills":38,"self_contained":44},"1.0.0","universal",{"entry_point":36,"full_content":37},85,8500,[27,39,40,41,42,43],"typescript","nodejs-backend","django","fastapi","flask",true,"claude-code",{"references":47,"entry_point":53},[48,49,50,51,52],"authentication.md","graphql-patterns.md","grpc-patterns.md","rest-patterns.md","versioning-strategies.md",{"summary":7,"quick_start":54,"when_to_use":55},"1. Review the core concepts below. 2. Apply patterns to your use case. 3. Follow best practices for implementation.","When designing, implementing, or documenting APIs.","main","f3f3769d02e636b7fc3aa4bb845009943b252e8f","workspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns",0,"https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team","https:\u002F\u002Fgithub.com\u002FaAAaqwq","https:\u002F\u002Fdaniel-li-portfolio.pages.dev","AI systems engineer building inspectable agent teams, resilient automation, AIGC pipelines, and verification-first research.","2026-06-18 10:28:29",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":44},[67,70,73],{"tool":68,"command":69},"npx","npx skills add aAAaqwq\u002Fopenclaw-team --skill api-design-patterns",{"tool":71,"command":72},"bunx","bunx skills add aAAaqwq\u002Fopenclaw-team --skill api-design-patterns",{"tool":74,"command":75},"pnpm","pnpm dlx skills add aAAaqwq\u002Fopenclaw-team --skill api-design-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns\u002FSKILL.md",[78,84,88,92,96],{"path":79,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fauthentication.md","REFERENCE","参考文档",23829,"https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fauthentication.md",{"path":85,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":86,"sourceHtmlUrl":87},"references\u002Fgraphql-patterns.md",24923,"https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fgraphql-patterns.md",{"path":89,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":90,"sourceHtmlUrl":91},"references\u002Fgrpc-patterns.md",28097,"https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fgrpc-patterns.md",{"path":93,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":94,"sourceHtmlUrl":95},"references\u002Frest-patterns.md",18788,"https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Frest-patterns.md",{"path":97,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":98,"sourceHtmlUrl":99},"references\u002Fversioning-strategies.md",17906,"https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Freferences\u002Fagi-super-team\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fversioning-strategies.md",[101,109,116,123,130,137],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":105,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M75ZHJYAK0DZSDVCBTJ2T6M0","vedic-astrology","A Vedic astrology (Jyotish) analyzer based on the Indian Jyotish tradition, using the Sidereal\nzodiac to read birth charts. Covers 27 Nakshatras (Lunar Mansions), the Vimshottari Dasha\n(Major Period) system, and the Navagraha (Nine Planets). Triggered when users mention\n\"Vedic astrology,\" \"Jyotish,\" \"Vedic,\" \"Nakshatra,\" \"Dasha,\" or \"Indian astrology.\"\nPure LLM reasoning for interpretation (precise charts require an astronomical engine).\nNo external API required.\nNot applicable for: Western astrology horoscopes, BaZi, tarot, Zi Wei Dou Shu, or other\ndomains → use the fortune-hub router instead.","MIT","https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fskills\u002Fvedic-astrology\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":105,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M75ZGWAPH5ZXQXE9EVW13DYD","tracking-crypto-prices","Track real-time cryptocurrency prices across exchanges with historical data and alerts.\nProvides price data infrastructure for dependent skills (portfolio, tax, DeFi, arbitrage).\nUse when checking crypto prices, monitoring markets, or fetching historical price data.\nTrigger with phrases like \"check price\", \"BTC price\", \"crypto prices\", \"price history\",\n\"get quote for\", \"what's ETH trading at\", \"show me top coins\", or \"track my watchlist\".","https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fskills\u002Ftracking-crypto-prices\u002FSKILL.md",[],[],{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":19},"01M75ZCSEPN43PZCMJF3QG5940","risk-assessment","Framework-directable information security risk assessment. Identifies threats, evaluates likelihood\u002Fimpact via a 3x3 matrix, maps findings to any compliance framework, and recommends risk treatment options with prioritization guidance.","https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fskills\u002Frisk-assessment\u002FSKILL.md",[],[],{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":105,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":19},"01M75ZC27KCZMJHQ25ZWC0YRE2","qimen-dunjia","奇门遁甲排盘分析器，基于洛书九宫四层盘面体系（天盘九星、地盘三奇六仪、人盘八门、神盘八神），\n支持时家奇门排盘，用于择时决策和事项预测。当用户提及「奇门遁甲」「奇门」「遁甲」「择时」\n「奇门排盘」「奇门预测」时触发。排盘为确定性计算 + LLM 综合解读，无外部 API 依赖。\n不适用于：梅花易数、六爻易经、风水分析、八字命理、塔罗占卜等其他领域 → 建议使用 fortune-hub 路由。","https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fskills\u002Fqimen-dunjia-oracle\u002FSKILL.md",[],[],{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":105,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":19},"01M75Z9ERP9C8N1E446MDXRMZN","negotiation","Tactical negotiation framework based on Chris Voss's \"Never Split the Difference.\" Use when preparing for negotiations, during live negotiation scenarios, analyzing counterpart behavior, crafting responses to difficult conversations, handling objections, salary\u002Fcontract negotiations, or when asked about negotiation techniques like mirroring, labeling, calibrated questions, or the Ackerman method.","https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fskills\u002Fnegotiation\u002FSKILL.md",[],[],{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":105,"licenseFileUrl":6,"sourceHtmlUrl":141,"categories":142,"keywords":143,"publishedAt":19},"01M75Z8S064PEAZACP8QPAXKQ4","meihua-yishu","梅花易数占卜工具，属于 fortune-telling-skills 运势测算套件。基于邵雍《梅花易数》体系，\n支持时间起卦、数字起卦、文字起卦等多种起卦方式，通过体用五行生克关系判断吉凶。\n起卦为确定性计算 + LLM 断卦解读，无外部 API 依赖。\n触发词：梅花易数、起卦、占卜、卦象、体用、八卦占卜、帮我起一卦、算一卦。\n不适用于：星座运势、塔罗占卜、八字命理 → 建议使用 fortune-hub。","https:\u002F\u002Fgithub.com\u002FaAAaqwq\u002Fopenclaw-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fskills\u002Fmeihua-yishu-divination\u002FSKILL.md",[],[]]