[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M730NEY4PX41QKRRW5PFYHTZ":3,"skill-same:01M730NEY4PX41QKRRW5PFYHTZ":98},{"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":14,"repositoryHtmlUrl":59,"repositoryHomepageUrl":6,"ownerHtmlUrl":60,"ownerBlogUrl":6,"ownerDescription":61,"updatedAt":62,"install":63,"resources":75},"01M730NEY4PX41QKRRW5PFYHTZ","api-design-patterns",null,"Comprehensive API design patterns covering REST, GraphQL, gRPC, versioning, authentication, and modern API best practices","julio211916\u002FTlantiCAD-Studio-V0.1-alpha","julio211916","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128201165?v=4","01M730ENY015MHFY82VKR6AGGR","José Carlos amador garcia","01M730ENYT83EWH6EXRHF9FTXV",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fapi-design-patterns\u002FSKILL.md",[],[],"2026-11-11 15:11:14",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","590aa4fe05d1ec71a02ee9cc76c9a20508b5bcea","skills\u002Fju\u002Fskills\u002Fapi-design-patterns","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha","https:\u002F\u002Fgithub.com\u002Fjulio211916","Estudiante de ing sistemas y psicologia","2026-05-22 04:43:54",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":44},[65,68,71],{"tool":66,"command":67},"npx","npx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill api-design-patterns",{"tool":69,"command":70},"bunx","bunx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill api-design-patterns",{"tool":72,"command":73},"pnpm","pnpm dlx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill api-design-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fapi-design-patterns\u002FSKILL.md",[76,82,86,90,94],{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fauthentication.md","REFERENCE","参考文档",23829,"https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fauthentication.md",{"path":83,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Fgraphql-patterns.md",24923,"https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fgraphql-patterns.md",{"path":87,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":88,"sourceHtmlUrl":89},"references\u002Fgrpc-patterns.md",28097,"https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fgrpc-patterns.md",{"path":91,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":92,"sourceHtmlUrl":93},"references\u002Frest-patterns.md",18788,"https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Frest-patterns.md",{"path":95,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":96,"sourceHtmlUrl":97},"references\u002Fversioning-strategies.md",17906,"https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fapi-design-patterns\u002Freferences\u002Fversioning-strategies.md",[99,107,114,121,128,135],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":103,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M735PMP7K29TEC1BC5A3VJ3Z","simpy","Process-based discrete-event simulation framework in Python. Use this skill when building simulations of systems with processes, queues, resources, and time-based events such as manufacturing systems, service operations, network traffic, logistics, or any system where entities interact with shared resources over time.","MIT","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fsimpy\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":103,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M735NX56AZHYMV3BQ8GYZ7J0","shopify-expert","Builds and debugs Shopify themes (.liquid files, theme.json, sections), develops custom Shopify apps (shopify.app.toml, OAuth, webhooks), and implements Storefront API integrations for headless storefronts. Use when building or customizing Shopify themes, creating Hydrogen or custom React storefronts, developing Shopify apps, implementing checkout UI extensions or Shopify Functions, optimizing performance, or integrating third-party services. Invoke for Liquid templating, Storefront API, app development, checkout customization, Shopify Plus features, App Bridge, Polaris, or Shopify CLI workflows.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshopify-expert\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":103,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":19},"01M735N9WTN69TVA2T5VS9W1CA","shap","Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this skill when explaining machine learning model predictions, computing feature importance, generating SHAP plots (waterfall, beeswarm, bar, scatter, force, heatmap), debugging models, analyzing model bias or fairness, comparing models, or implementing explainable AI. Works with tree-based models (XGBoost, LightGBM, Random Forest), deep learning (TensorFlow, PyTorch), linear models, and any black-box model.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshap\u002FSKILL.md",[],[],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":103,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":19},"01M735N3VQ8R56TXFF16BMF19H","shadcn-ui","Deep expertise on shadcn\u002Fui component library including installation, customization, theming, and accessibility patterns. Use when building UI with shadcn\u002Fui components, integrating Radix UI primitives, configuring Tailwind CSS v4 themes, or implementing dark mode. Covers Next.js App Router, Pages Router, and Vite setups.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshadcn-ui\u002FSKILL.md",[],[],{"skillNo":129,"name":130,"nameZh":6,"description":131,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":103,"licenseFileUrl":6,"sourceHtmlUrl":132,"categories":133,"keywords":134,"publishedAt":19},"01M735KH64KS6Z58H6BJWX89BV","seoul-subway-arrival","Look up Seoul real-time subway arrival information with the official Seoul Open Data API. Use when the user asks when a train arrives, which trains are approaching a station, or how crowded Seoul subway timing looks right now.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fseoul-subway-arrival\u002FSKILL.md",[],[],{"skillNo":136,"name":137,"nameZh":6,"description":138,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":103,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":141,"publishedAt":19},"01M735K7KAFBZNACQ66PMDQMQD","seo-optimization","Comprehensive 7-phase SEO optimization workflow covering technical SEO auditing, keyword research strategy, on-page optimization, content SEO and E-E-A-T, structured data implementation, link building, and AI search optimization. Use when auditing search engine visibility, diagnosing ranking issues, implementing schema markup, conducting keyword research, optimizing content for E-E-A-T signals, or adapting for AI-driven search (AI Overviews, SGE).","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fseo-optimization\u002FSKILL.md",[],[]]