[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BEWZMES23QHDWRT58YVABP":3,"skill-same:01M7BEWZMES23QHDWRT58YVABP":50},{"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":27,"commitSha":28,"skillDirectory":29,"forksCount":30,"repositoryHtmlUrl":31,"repositoryHomepageUrl":32,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M7BEWZMES23QHDWRT58YVABP","api-design",null,"REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-AI-应用工具\u002FYYC3-AI-应用工具-Everything-claude-code\u002F.kiro\u002Fskills\u002Fapi-design\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: api-design\ndescription: >\n  REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs.\nmetadata:\n  origin: ECC\n---\n\n# API Design Patterns\n\nConventions and best practices for designing consistent, developer-friendly REST APIs.\n\n## When to Activate\n\n- Designing new API endpoints\n- Reviewing existing API contracts\n- Adding pagination, filtering, or sorting\n- Implementing error handling for APIs\n- Planning API versioning strategy\n- Building public or partner-facing APIs\n\n## Resource Design\n\n### URL Structure\n\n```\n# Resources are nouns, plural, lowercase, kebab-case\nGET    \u002Fapi\u002Fv1\u002Fusers\nGET    \u002Fapi\u002Fv1\u002Fusers\u002F:id\nPOST   \u002Fapi\u002Fv1\u002Fusers\nPUT    \u002Fapi\u002Fv1\u002Fusers\u002F:id\nPATCH  \u002Fapi\u002Fv1\u002Fusers\u002F:id\nDELETE \u002Fapi\u002Fv1\u002Fusers\u002F:id\n\n# Sub-resources for relationships\nGET    \u002Fapi\u002Fv1\u002Fusers\u002F:id\u002Forders\nPOST   \u002Fapi\u002Fv1\u002Fusers\u002F:id\u002Forders\n\n# Actions that don't map to CRUD (use verbs sparingly)\nPOST   \u002Fapi\u002Fv1\u002Forders\u002F:id\u002Fcancel\nPOST   \u002Fapi\u002Fv1\u002Fauth\u002Flogin\nPOST   \u002Fapi\u002Fv1\u002Fauth\u002Frefresh\n```\n\n### Naming Rules\n\n```\n# GOOD\n\u002Fapi\u002Fv1\u002Fteam-members          # kebab-case for multi-word resources\n\u002Fapi\u002Fv1\u002Forders?status=active  # query params for filtering\n\u002Fapi\u002Fv1\u002Fusers\u002F123\u002Forders      # nested resources for ownership\n\n# BAD\n\u002Fapi\u002Fv1\u002FgetUsers              # verb in URL\n\u002Fapi\u002Fv1\u002Fuser                  # singular (use plural)\n\u002Fapi\u002Fv1\u002Fteam_members          # snake_case in URLs\n\u002Fapi\u002Fv1\u002Fusers\u002F123\u002FgetOrders   # verb in nested resource\n```\n\n## HTTP Methods and Status Codes\n\n### Method Semantics\n\n| Method | Idempotent | Safe | Use For |\n|--------|-----------|------|---------|\n| GET | Yes | Yes | Retrieve resources |\n| POST | No | No | Create resources, trigger actions |\n| PUT | Yes | No | Full replacement of a resource |\n| PATCH | No* | No | Partial update of a resource |\n| DELETE | Yes | No | Remove a resource |\n\n*PATCH can be made idempotent with proper implementation\n\n### Status Code Reference\n\n```\n# Success\n200 OK                    — GET, PUT, PATCH (with response body)\n201 Created               — POST (include Location header)\n204 No Content            — DELETE, PUT (no response body)\n\n# Client Errors\n400 Bad Request           — Validation failure, malformed JSON\n401 Unauthorized          — Missing or invalid authentication\n403 Forbidden             — Authenticated but not authorized\n404 Not Found             — Resource doesn't exist\n409 Conflict              — Duplicate entry, state conflict\n422 Unprocessable Entity  — Semantically invalid (valid JSON, bad data)\n429 Too Many Requests     — Rate limit exceeded\n\n# Server Errors\n500 Internal Server Error — Unexpected failure (never expose details)\n502 Bad Gateway           — Upstream service failed\n503 Service Unavailable   — Temporary overload, include Retry-After\n```\n\n### Common Mistakes\n\n```\n# BAD: 200 for everything\n{ \"status\": 200, \"success\": false, \"error\": \"Not found\" }\n\n# GOOD: Use HTTP status codes semantically\nHTTP\u002F1.1 404 Not Found\n{ \"error\": { \"code\": \"not_found\", \"message\": \"User not found\" } }\n\n# BAD: 500 for validation errors\n# GOOD: 400 or 422 with field-level details\n\n# BAD: 200 for created resources\n# GOOD: 201 with Location header\nHTTP\u002F1.1 201 Created\nLocation: \u002Fapi\u002Fv1\u002Fusers\u002Fabc-123\n```\n\n## Response Format\n\n### Success Response\n\n```json\n{\n  \"data\": {\n    \"id\": \"abc-123\",\n    \"email\": \"alice@example.com\",\n    \"name\": \"Alice\",\n    \"created_at\": \"2025-01-15T10:30:00Z\"\n  }\n}\n```\n\n### Collection Response (with Pagination)\n\n```json\n{\n  \"data\": [\n    { \"id\": \"abc-123\", \"name\": \"Alice\" },\n    { \"id\": \"def-456\", \"name\": \"Bob\" }\n  ],\n  \"meta\": {\n    \"total\": 142,\n    \"page\": 1,\n    \"per_page\": 20,\n    \"total_pages\": 8\n  },\n  \"links\": {\n    \"self\": \"\u002Fapi\u002Fv1\u002Fusers?page=1&per_page=20\",\n    \"next\": \"\u002Fapi\u002Fv1\u002Fusers?page=2&per_page=20\",\n    \"last\": \"\u002Fapi\u002Fv1\u002Fusers?page=8&per_page=20\"\n  }\n}\n```\n\n### Error Response\n\n```json\n{\n  \"error\": {\n    \"code\": \"validation_error\",\n    \"message\": \"Request validation failed\",\n    \"details\": [\n      {\n        \"field\": \"email\",\n        \"message\": \"Must be a valid email address\",\n        \"code\": \"invalid_format\"\n      },\n      {\n        \"field\": \"age\",\n        \"message\": \"Must be between 0 and 150\",\n        \"code\": \"out_of_range\"\n      }\n    ]\n  }\n}\n```\n\n### Response Envelope Variants\n\n```typescript\n\u002F\u002F Option A: Envelope with data wrapper (recommended for public APIs)\ninterface ApiResponse\u003CT> {\n  data: T;\n  meta?: PaginationMeta;\n  links?: PaginationLinks;\n}\n\ninterface ApiError {\n  error: {\n    code: string;\n    message: string;\n    details?: FieldError[];\n  };\n}\n\n\u002F\u002F Option B: Flat response (simpler, common for internal APIs)\n\u002F\u002F Success: just return the resource directly\n\u002F\u002F Error: return error object\n\u002F\u002F Distinguish by HTTP status code\n```\n\n## Pagination\n\n### Offset-Based (Simple)\n\n```\nGET \u002Fapi\u002Fv1\u002Fusers?page=2&per_page=20\n\n# Implementation\nSELECT * FROM users\nORDER BY created_at DESC\nLIMIT 20 OFFSET 20;\n```\n\n**Pros:** Easy to implement, supports \"jump to page N\"\n**Cons:** Slow on large offsets (OFFSET 100000), inconsistent with concurrent inserts\n\n### Cursor-Based (Scalable)\n\n```\nGET \u002Fapi\u002Fv1\u002Fusers?cursor=eyJpZCI6MTIzfQ&limit=20\n\n# Implementation\nSELECT * FROM users\nWHERE id > :cursor_id\nORDER BY id ASC\nLIMIT 21;  -- fetch one extra to determine has_next\n```\n\n```json\n{\n  \"data\": [...],\n  \"meta\": {\n    \"has_next\": true,\n    \"next_cursor\": \"eyJpZCI6MTQzfQ\"\n  }\n}\n```\n\n**Pros:** Consistent performance regardless of position, stable with concurrent inserts\n**Cons:** Cannot jump to arbitrary page, cursor is opaque\n\n### When to Use Which\n\n| Use Case | Pagination Type |\n|----------|----------------|\n| Admin dashboards, small datasets (\u003C10K) | Offset |\n| Infinite scroll, feeds, large datasets | Cursor |\n| Public APIs | Cursor (default) with offset (optional) |\n| Search results | Offset (users expect page numbers) |\n\n## Filtering, Sorting, and Search\n\n### Filtering\n\n```\n# Simple equality\nGET \u002Fapi\u002Fv1\u002Forders?status=active&customer_id=abc-123\n\n# Comparison operators (use bracket notation)\nGET \u002Fapi\u002Fv1\u002Fproducts?price[gte]=10&price[lte]=100\nGET \u002Fapi\u002Fv1\u002Forders?created_at[after]=2025-01-01\n\n# Multiple values (comma-separated)\nGET \u002Fapi\u002Fv1\u002Fproducts?category=electronics,clothing\n\n# Nested fields (dot notation)\nGET \u002Fapi\u002Fv1\u002Forders?customer.country=US\n```\n\n### Sorting\n\n```\n# Single field (prefix - for descending)\nGET \u002Fapi\u002Fv1\u002Fproducts?sort=-created_at\n\n# Multiple fields (comma-separated)\nGET \u002Fapi\u002Fv1\u002Fproducts?sort=-featured,price,-created_at\n```\n\n### Full-Text Search\n\n```\n# Search query parameter\nGET \u002Fapi\u002Fv1\u002Fproducts?q=wireless+headphones\n\n# Field-specific search\nGET \u002Fapi\u002Fv1\u002Fusers?email=alice\n```\n\n### Sparse Fieldsets\n\n```\n# Return only specified fields (reduces payload)\nGET \u002Fapi\u002Fv1\u002Fusers?fields=id,name,email\nGET \u002Fapi\u002Fv1\u002Forders?fields=id,total,status&include=customer.name\n```\n\n## Authentication and Authorization\n\n### Token-Based Auth\n\n```\n# Bearer token in Authorization header\nGET \u002Fapi\u002Fv1\u002Fusers\nAuthorization: Bearer eyJhbGciOiJIUzI1NiIs...\n\n# API key (for server-to-server)\nGET \u002Fapi\u002Fv1\u002Fdata\nX-API-Key: sk_live_abc123\n```\n\n### Authorization Patterns\n\n```typescript\n\u002F\u002F Resource-level: check ownership\napp.get(\"\u002Fapi\u002Fv1\u002Forders\u002F:id\", async (req, res) => {\n  const order = await Order.findById(req.params.id);\n  if (!order) return res.status(404).json({ error: { code: \"not_found\" } });\n  if (order.userId !== req.user.id) return res.status(403).json({ error: { code: \"forbidden\" } });\n  return res.json({ data: order });\n});\n\n\u002F\u002F Role-based: check permissions\napp.delete(\"\u002Fapi\u002Fv1\u002Fusers\u002F:id\", requireRole(\"admin\"), async (req, res) => {\n  await User.delete(req.params.id);\n  return res.status(204).send();\n});\n```\n\n## Rate Limiting\n\n### Headers\n\n```\nHTTP\u002F1.1 200 OK\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 95\nX-RateLimit-Reset: 1640000000\n\n# When exceeded\nHTTP\u002F1.1 429 Too Many Requests\nRetry-After: 60\n{\n  \"error\": {\n    \"code\": \"rate_limit_exceeded\",\n    \"message\": \"Rate limit exceeded. Try again in 60 seconds.\"\n  }\n}\n```\n\n### Rate Limit Tiers\n\n| Tier | Limit | Window | Use Case |\n|------|-------|--------|----------|\n| Anonymous | 30\u002Fmin | Per IP | Public endpoints |\n| Authenticated | 100\u002Fmin | Per user | Standard API access |\n| Premium | 1000\u002Fmin | Per API key | Paid API plans |\n| Internal | 10000\u002Fmin | Per service | Service-to-service |\n\n## Versioning\n\n### URL Path Versioning (Recommended)\n\n```\n\u002Fapi\u002Fv1\u002Fusers\n\u002Fapi\u002Fv2\u002Fusers\n```\n\n**Pros:** Explicit, easy to route, cacheable\n**Cons:** URL changes between versions\n\n### Header Versioning\n\n```\nGET \u002Fapi\u002Fusers\nAccept: application\u002Fvnd.myapp.v2+json\n```\n\n**Pros:** Clean URLs\n**Cons:** Harder to test, easy to forget\n\n### Versioning Strategy\n\n```\n1. Start with \u002Fapi\u002Fv1\u002F — don't version until you need to\n2. Maintain at most 2 active versions (current + previous)\n3. Deprecation timeline:\n   - Announce deprecation (6 months notice for public APIs)\n   - Add Sunset header: Sunset: Sat, 01 Jan 2026 00:00:00 GMT\n   - Return 410 Gone after sunset date\n4. Non-breaking changes don't need a new version:\n   - Adding new fields to responses\n   - Adding new optional query parameters\n   - Adding new endpoints\n5. Breaking changes require a new version:\n   - Removing or renaming fields\n   - Changing field types\n   - Changing URL structure\n   - Changing authentication method\n```\n\n## Implementation Patterns\n\n### TypeScript (Next.js API Route)\n\n```typescript\nimport { z } from \"zod\";\nimport { NextRequest, NextResponse } from \"next\u002Fserver\";\n\nconst createUserSchema = z.object({\n  email: z.string().email(),\n  name: z.string().min(1).max(100),\n});\n\nexport async function POST(req: NextRequest) {\n  const body = await req.json();\n  const parsed = createUserSchema.safeParse(body);\n\n  if (!parsed.success) {\n    return NextResponse.json({\n      error: {\n        code: \"validation_error\",\n        message: \"Request validation failed\",\n        details: parsed.error.issues.map(i => ({\n          field: i.path.join(\".\"),\n          message: i.message,\n          code: i.code,\n        })),\n      },\n    }, { status: 422 });\n  }\n\n  const user = await createUser(parsed.data);\n\n  return NextResponse.json(\n    { data: user },\n    {\n      status: 201,\n      headers: { Location: `\u002Fapi\u002Fv1\u002Fusers\u002F${user.id}` },\n    },\n  );\n}\n```\n\n### Python (Django REST Framework)\n\n```python\nfrom rest_framework import serializers, viewsets, status\nfrom rest_framework.response import Response\n\nclass CreateUserSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    name = serializers.CharField(max_length=100)\n\nclass UserSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = [\"id\", \"email\", \"name\", \"created_at\"]\n\nclass UserViewSet(viewsets.ModelViewSet):\n    serializer_class = UserSerializer\n    permission_classes = [IsAuthenticated]\n\n    def get_serializer_class(self):\n        if self.action == \"create\":\n            return CreateUserSerializer\n        return UserSerializer\n\n    def create(self, request):\n        serializer = CreateUserSerializer(data=request.data)\n        serializer.is_valid(raise_exception=True)\n        user = UserService.create(**serializer.validated_data)\n        return Response(\n            {\"data\": UserSerializer(user).data},\n            status=status.HTTP_201_CREATED,\n            headers={\"Location\": f\"\u002Fapi\u002Fv1\u002Fusers\u002F{user.id}\"},\n        )\n```\n\n### Go (net\u002Fhttp)\n\n```go\nfunc (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {\n    var req CreateUserRequest\n    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n        writeError(w, http.StatusBadRequest, \"invalid_json\", \"Invalid request body\")\n        return\n    }\n\n    if err := req.Validate(); err != nil {\n        writeError(w, http.StatusUnprocessableEntity, \"validation_error\", err.Error())\n        return\n    }\n\n    user, err := h.service.Create(r.Context(), req)\n    if err != nil {\n        switch {\n        case errors.Is(err, domain.ErrEmailTaken):\n            writeError(w, http.StatusConflict, \"email_taken\", \"Email already registered\")\n        default:\n            writeError(w, http.StatusInternalServerError, \"internal_error\", \"Internal error\")\n        }\n        return\n    }\n\n    w.Header().Set(\"Location\", fmt.Sprintf(\"\u002Fapi\u002Fv1\u002Fusers\u002F%s\", user.ID))\n    writeJSON(w, http.StatusCreated, map[string]any{\"data\": user})\n}\n```\n\n## API Design Checklist\n\nBefore shipping a new endpoint:\n\n- [ ] Resource URL follows naming conventions (plural, kebab-case, no verbs)\n- [ ] Correct HTTP method used (GET for reads, POST for creates, etc.)\n- [ ] Appropriate status codes returned (not 200 for everything)\n- [ ] Input validated with schema (Zod, Pydantic, Bean Validation)\n- [ ] Error responses follow standard format with codes and messages\n- [ ] Pagination implemented for list endpoints (cursor or offset)\n- [ ] Authentication required (or explicitly marked as public)\n- [ ] Authorization checked (user can only access their own resources)\n- [ ] Rate limiting configured\n- [ ] Response does not leak internal details (stack traces, SQL errors)\n- [ ] Consistent naming with existing endpoints (camelCase vs snake_case)\n- [ ] Documented (OpenAPI\u002FSwagger spec updated)\n","# API Design Patterns\n\nConventions and best practices for designing consistent, developer-friendly REST APIs.\n\n## When to Activate\n\n- Designing new API endpoints\n- Reviewing existing API contracts\n- Adding pagination, filtering, or sorting\n- Implementing error handling for APIs\n- Planning API versioning strategy\n- Building public or partner-facing APIs\n\n## Resource Design\n\n### URL Structure\n\n```\n# Resources are nouns, plural, lowercase, kebab-case\nGET    \u002Fapi\u002Fv1\u002Fusers\nGET    \u002Fapi\u002Fv1\u002Fusers\u002F:id\nPOST   \u002Fapi\u002Fv1\u002Fusers\nPUT    \u002Fapi\u002Fv1\u002Fusers\u002F:id\nPATCH  \u002Fapi\u002Fv1\u002Fusers\u002F:id\nDELETE \u002Fapi\u002Fv1\u002Fusers\u002F:id\n\n# Sub-resources for relationships\nGET    \u002Fapi\u002Fv1\u002Fusers\u002F:id\u002Forders\nPOST   \u002Fapi\u002Fv1\u002Fusers\u002F:id\u002Forders\n\n# Actions that don't map to CRUD (use verbs sparingly)\nPOST   \u002Fapi\u002Fv1\u002Forders\u002F:id\u002Fcancel\nPOST   \u002Fapi\u002Fv1\u002Fauth\u002Flogin\nPOST   \u002Fapi\u002Fv1\u002Fauth\u002Frefresh\n```\n\n### Naming Rules\n\n```\n# GOOD\n\u002Fapi\u002Fv1\u002Fteam-members          # kebab-case for multi-word resources\n\u002Fapi\u002Fv1\u002Forders?status=active  # query params for filtering\n\u002Fapi\u002Fv1\u002Fusers\u002F123\u002Forders      # nested resources for ownership\n\n# BAD\n\u002Fapi\u002Fv1\u002FgetUsers              # verb in URL\n\u002Fapi\u002Fv1\u002Fuser                  # singular (use plural)\n\u002Fapi\u002Fv1\u002Fteam_members          # snake_case in URLs\n\u002Fapi\u002Fv1\u002Fusers\u002F123\u002FgetOrders   # verb in nested resource\n```\n\n## HTTP Methods and Status Codes\n\n### Method Semantics\n\n| Method | Idempotent | Safe | Use For |\n|--------|-----------|------|---------|\n| GET | Yes | Yes | Retrieve resources |\n| POST | No | No | Create resources, trigger actions |\n| PUT | Yes | No | Full replacement of a resource |\n| PATCH | No* | No | Partial update of a resource |\n| DELETE | Yes | No | Remove a resource |\n\n*PATCH can be made idempotent with proper implementation\n\n### Status Code Reference\n\n```\n# Success\n200 OK                    — GET, PUT, PATCH (with response body)\n201 Created               — POST (include Location header)\n204 No Content            — DELETE, PUT (no response body)\n\n# Client Errors\n400 Bad Request           — Validation failure, malformed JSON\n401 Unauthorized          — Missing or invalid authentication\n403 Forbidden             — Authenticated but not authorized\n404 Not Found             — Resource doesn't exist\n409 Conflict              — Duplicate entry, state conflict\n422 Unprocessable Entity  — Semantically invalid (valid JSON, bad data)\n429 Too Many Requests     — Rate limit exceeded\n\n# Server Errors\n500 Internal Server Error — Unexpected failure (never expose details)\n502 Bad Gateway           — Upstream service failed\n503 Service Unavailable   — Temporary overload, include Retry-After\n```\n\n### Common Mistakes\n\n```\n# BAD: 200 for everything\n{ \"status\": 200, \"success\": false, \"error\": \"Not found\" }\n\n# GOOD: Use HTTP status codes semantically\nHTTP\u002F1.1 404 Not Found\n{ \"error\": { \"code\": \"not_found\", \"message\": \"User not found\" } }\n\n# BAD: 500 for validation errors\n# GOOD: 400 or 422 with field-level details\n\n# BAD: 200 for created resources\n# GOOD: 201 with Location header\nHTTP\u002F1.1 201 Created\nLocation: \u002Fapi\u002Fv1\u002Fusers\u002Fabc-123\n```\n\n## Response Format\n\n### Success Response\n\n```json\n{\n  \"data\": {\n    \"id\": \"abc-123\",\n    \"email\": \"alice@example.com\",\n    \"name\": \"Alice\",\n    \"created_at\": \"2025-01-15T10:30:00Z\"\n  }\n}\n```\n\n### Collection Response (with Pagination)\n\n```json\n{\n  \"data\": [\n    { \"id\": \"abc-123\", \"name\": \"Alice\" },\n    { \"id\": \"def-456\", \"name\": \"Bob\" }\n  ],\n  \"meta\": {\n    \"total\": 142,\n    \"page\": 1,\n    \"per_page\": 20,\n    \"total_pages\": 8\n  },\n  \"links\": {\n    \"self\": \"\u002Fapi\u002Fv1\u002Fusers?page=1&per_page=20\",\n    \"next\": \"\u002Fapi\u002Fv1\u002Fusers?page=2&per_page=20\",\n    \"last\": \"\u002Fapi\u002Fv1\u002Fusers?page=8&per_page=20\"\n  }\n}\n```\n\n### Error Response\n\n```json\n{\n  \"error\": {\n    \"code\": \"validation_error\",\n    \"message\": \"Request validation failed\",\n    \"details\": [\n      {\n        \"field\": \"email\",\n        \"message\": \"Must be a valid email address\",\n        \"code\": \"invalid_format\"\n      },\n      {\n        \"field\": \"age\",\n        \"message\": \"Must be between 0 and 150\",\n        \"code\": \"out_of_range\"\n      }\n    ]\n  }\n}\n```\n\n### Response Envelope Variants\n\n```typescript\n\u002F\u002F Option A: Envelope with data wrapper (recommended for public APIs)\ninterface ApiResponse\u003CT> {\n  data: T;\n  meta?: PaginationMeta;\n  links?: PaginationLinks;\n}\n\ninterface ApiError {\n  error: {\n    code: string;\n    message: string;\n    details?: FieldError[];\n  };\n}\n\n\u002F\u002F Option B: Flat response (simpler, common for internal APIs)\n\u002F\u002F Success: just return the resource directly\n\u002F\u002F Error: return error object\n\u002F\u002F Distinguish by HTTP status code\n```\n\n## Pagination\n\n### Offset-Based (Simple)\n\n```\nGET \u002Fapi\u002Fv1\u002Fusers?page=2&per_page=20\n\n# Implementation\nSELECT * FROM users\nORDER BY created_at DESC\nLIMIT 20 OFFSET 20;\n```\n\n**Pros:** Easy to implement, supports \"jump to page N\"\n**Cons:** Slow on large offsets (OFFSET 100000), inconsistent with concurrent inserts\n\n### Cursor-Based (Scalable)\n\n```\nGET \u002Fapi\u002Fv1\u002Fusers?cursor=eyJpZCI6MTIzfQ&limit=20\n\n# Implementation\nSELECT * FROM users\nWHERE id > :cursor_id\nORDER BY id ASC\nLIMIT 21;  -- fetch one extra to determine has_next\n```\n\n```json\n{\n  \"data\": [...],\n  \"meta\": {\n    \"has_next\": true,\n    \"next_cursor\": \"eyJpZCI6MTQzfQ\"\n  }\n}\n```\n\n**Pros:** Consistent performance regardless of position, stable with concurrent inserts\n**Cons:** Cannot jump to arbitrary page, cursor is opaque\n\n### When to Use Which\n\n| Use Case | Pagination Type |\n|----------|----------------|\n| Admin dashboards, small datasets (\u003C10K) | Offset |\n| Infinite scroll, feeds, large datasets | Cursor |\n| Public APIs | Cursor (default) with offset (optional) |\n| Search results | Offset (users expect page numbers) |\n\n## Filtering, Sorting, and Search\n\n### Filtering\n\n```\n# Simple equality\nGET \u002Fapi\u002Fv1\u002Forders?status=active&customer_id=abc-123\n\n# Comparison operators (use bracket notation)\nGET \u002Fapi\u002Fv1\u002Fproducts?price[gte]=10&price[lte]=100\nGET \u002Fapi\u002Fv1\u002Forders?created_at[after]=2025-01-01\n\n# Multiple values (comma-separated)\nGET \u002Fapi\u002Fv1\u002Fproducts?category=electronics,clothing\n\n# Nested fields (dot notation)\nGET \u002Fapi\u002Fv1\u002Forders?customer.country=US\n```\n\n### Sorting\n\n```\n# Single field (prefix - for descending)\nGET \u002Fapi\u002Fv1\u002Fproducts?sort=-created_at\n\n# Multiple fields (comma-separated)\nGET \u002Fapi\u002Fv1\u002Fproducts?sort=-featured,price,-created_at\n```\n\n### Full-Text Search\n\n```\n# Search query parameter\nGET \u002Fapi\u002Fv1\u002Fproducts?q=wireless+headphones\n\n# Field-specific search\nGET \u002Fapi\u002Fv1\u002Fusers?email=alice\n```\n\n### Sparse Fieldsets\n\n```\n# Return only specified fields (reduces payload)\nGET \u002Fapi\u002Fv1\u002Fusers?fields=id,name,email\nGET \u002Fapi\u002Fv1\u002Forders?fields=id,total,status&include=customer.name\n```\n\n## Authentication and Authorization\n\n### Token-Based Auth\n\n```\n# Bearer token in Authorization header\nGET \u002Fapi\u002Fv1\u002Fusers\nAuthorization: Bearer eyJhbGciOiJIUzI1NiIs...\n\n# API key (for server-to-server)\nGET \u002Fapi\u002Fv1\u002Fdata\nX-API-Key: sk_live_abc123\n```\n\n### Authorization Patterns\n\n```typescript\n\u002F\u002F Resource-level: check ownership\napp.get(\"\u002Fapi\u002Fv1\u002Forders\u002F:id\", async (req, res) => {\n  const order = await Order.findById(req.params.id);\n  if (!order) return res.status(404).json({ error: { code: \"not_found\" } });\n  if (order.userId !== req.user.id) return res.status(403).json({ error: { code: \"forbidden\" } });\n  return res.json({ data: order });\n});\n\n\u002F\u002F Role-based: check permissions\napp.delete(\"\u002Fapi\u002Fv1\u002Fusers\u002F:id\", requireRole(\"admin\"), async (req, res) => {\n  await User.delete(req.params.id);\n  return res.status(204).send();\n});\n```\n\n## Rate Limiting\n\n### Headers\n\n```\nHTTP\u002F1.1 200 OK\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 95\nX-RateLimit-Reset: 1640000000\n\n# When exceeded\nHTTP\u002F1.1 429 Too Many Requests\nRetry-After: 60\n{\n  \"error\": {\n    \"code\": \"rate_limit_exceeded\",\n    \"message\": \"Rate limit exceeded. Try again in 60 seconds.\"\n  }\n}\n```\n\n### Rate Limit Tiers\n\n| Tier | Limit | Window | Use Case |\n|------|-------|--------|----------|\n| Anonymous | 30\u002Fmin | Per IP | Public endpoints |\n| Authenticated | 100\u002Fmin | Per user | Standard API access |\n| Premium | 1000\u002Fmin | Per API key | Paid API plans |\n| Internal | 10000\u002Fmin | Per service | Service-to-service |\n\n## Versioning\n\n### URL Path Versioning (Recommended)\n\n```\n\u002Fapi\u002Fv1\u002Fusers\n\u002Fapi\u002Fv2\u002Fusers\n```\n\n**Pros:** Explicit, easy to route, cacheable\n**Cons:** URL changes between versions\n\n### Header Versioning\n\n```\nGET \u002Fapi\u002Fusers\nAccept: application\u002Fvnd.myapp.v2+json\n```\n\n**Pros:** Clean URLs\n**Cons:** Harder to test, easy to forget\n\n### Versioning Strategy\n\n```\n1. Start with \u002Fapi\u002Fv1\u002F — don't version until you need to\n2. Maintain at most 2 active versions (current + previous)\n3. Deprecation timeline:\n   - Announce deprecation (6 months notice for public APIs)\n   - Add Sunset header: Sunset: Sat, 01 Jan 2026 00:00:00 GMT\n   - Return 410 Gone after sunset date\n4. Non-breaking changes don't need a new version:\n   - Adding new fields to responses\n   - Adding new optional query parameters\n   - Adding new endpoints\n5. Breaking changes require a new version:\n   - Removing or renaming fields\n   - Changing field types\n   - Changing URL structure\n   - Changing authentication method\n```\n\n## Implementation Patterns\n\n### TypeScript (Next.js API Route)\n\n```typescript\nimport { z } from \"zod\";\nimport { NextRequest, NextResponse } from \"next\u002Fserver\";\n\nconst createUserSchema = z.object({\n  email: z.string().email(),\n  name: z.string().min(1).max(100),\n});\n\nexport async function POST(req: NextRequest) {\n  const body = await req.json();\n  const parsed = createUserSchema.safeParse(body);\n\n  if (!parsed.success) {\n    return NextResponse.json({\n      error: {\n        code: \"validation_error\",\n        message: \"Request validation failed\",\n        details: parsed.error.issues.map(i => ({\n          field: i.path.join(\".\"),\n          message: i.message,\n          code: i.code,\n        })),\n      },\n    }, { status: 422 });\n  }\n\n  const user = await createUser(parsed.data);\n\n  return NextResponse.json(\n    { data: user },\n    {\n      status: 201,\n      headers: { Location: `\u002Fapi\u002Fv1\u002Fusers\u002F${user.id}` },\n    },\n  );\n}\n```\n\n### Python (Django REST Framework)\n\n```python\nfrom rest_framework import serializers, viewsets, status\nfrom rest_framework.response import Response\n\nclass CreateUserSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    name = serializers.CharField(max_length=100)\n\nclass UserSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = [\"id\", \"email\", \"name\", \"created_at\"]\n\nclass UserViewSet(viewsets.ModelViewSet):\n    serializer_class = UserSerializer\n    permission_classes = [IsAuthenticated]\n\n    def get_serializer_class(self):\n        if self.action == \"create\":\n            return CreateUserSerializer\n        return UserSerializer\n\n    def create(self, request):\n        serializer = CreateUserSerializer(data=request.data)\n        serializer.is_valid(raise_exception=True)\n        user = UserService.create(**serializer.validated_data)\n        return Response(\n            {\"data\": UserSerializer(user).data},\n            status=status.HTTP_201_CREATED,\n            headers={\"Location\": f\"\u002Fapi\u002Fv1\u002Fusers\u002F{user.id}\"},\n        )\n```\n\n### Go (net\u002Fhttp)\n\n```go\nfunc (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {\n    var req CreateUserRequest\n    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n        writeError(w, http.StatusBadRequest, \"invalid_json\", \"Invalid request body\")\n        return\n    }\n\n    if err := req.Validate(); err != nil {\n        writeError(w, http.StatusUnprocessableEntity, \"validation_error\", err.Error())\n        return\n    }\n\n    user, err := h.service.Create(r.Context(), req)\n    if err != nil {\n        switch {\n        case errors.Is(err, domain.ErrEmailTaken):\n            writeError(w, http.StatusConflict, \"email_taken\", \"Email already registered\")\n        default:\n            writeError(w, http.StatusInternalServerError, \"internal_error\", \"Internal error\")\n        }\n        return\n    }\n\n    w.Header().Set(\"Location\", fmt.Sprintf(\"\u002Fapi\u002Fv1\u002Fusers\u002F%s\", user.ID))\n    writeJSON(w, http.StatusCreated, map[string]any{\"data\": user})\n}\n```\n\n## API Design Checklist\n\nBefore shipping a new endpoint:\n\n- [ ] Resource URL follows naming conventions (plural, kebab-case, no verbs)\n- [ ] Correct HTTP method used (GET for reads, POST for creates, etc.)\n- [ ] Appropriate status codes returned (not 200 for everything)\n- [ ] Input validated with schema (Zod, Pydantic, Bean Validation)\n- [ ] Error responses follow standard format with codes and messages\n- [ ] Pagination implemented for list endpoints (cursor or offset)\n- [ ] Authentication required (or explicitly marked as public)\n- [ ] Authorization checked (user can only access their own resources)\n- [ ] Rate limiting configured\n- [ ] Response does not leak internal details (stack traces, SQL errors)\n- [ ] Consistent naming with existing endpoints (camelCase vs snake_case)\n- [ ] Documented (OpenAPI\u002FSwagger spec updated)\n",{"name":5,"metadata":24,"description":26},{"origin":25},"ECC","REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs.\n","main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-AI-应用工具\u002FYYC3-AI-应用工具-Everything-claude-code\u002F.kiro\u002Fskills\u002Fapi-design",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill api-design",{"tool":42,"command":43},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill api-design",{"tool":45,"command":46},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill api-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-AI-应用工具\u002FYYC3-AI-应用工具-Everything-claude-code\u002F.kiro\u002Fskills\u002Fapi-design\u002FSKILL.md",true,[],[51,58,65,72,79,86],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]