[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HQ7X16793DTXR3ST2HFS56":3,"skill-same:01M6HQ7X16793DTXR3ST2HFS56":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":33,"publishedAt":54,"linkOnly":55,"markdownContent":56,"markdownBody":57,"frontMatter":58,"refName":59,"commitSha":60,"skillDirectory":61,"forksCount":62,"repositoryHtmlUrl":63,"repositoryHomepageUrl":6,"ownerHtmlUrl":64,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":65,"install":66,"resources":79},"01M6HQ7X16793DTXR3ST2HFS56","api-design",null,"REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs.","welflau\u002Fai-dev-system","welflau","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F7010385?v=4","01M6HPTDGF18RFY07M229P8CTM","01M6HPTDMRMZCJPYBFEA9XVVYT",3,"MIT","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fconfig_packs\u002Fweb-dev\u002Fshared\u002Fskills\u002Fapi-design\u002FSKILL.md",[17,22,25,30],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",{"categoryNo":31,"categoryName":32,"taxonomyType":28,"taxonomyTypeDesc":29},"01JBSEEDCAT000000000000032","设计师",[34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53],"api design","api","design","patterns","rate","for","rest api design","naming","api design patterns","codes","error","rest api","rate limiting","pagination","design patterns","filtering","versioning","REST","Production","status","2026-11-10 10:12:30",false,"---\nname: api-design\ndescription: REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs.\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,"description":7},"main","18d0e63d1313ca87098f614aa7c1e2dcf6de79c7","backend\u002Fconfig_packs\u002Fweb-dev\u002Fshared\u002Fskills\u002Fapi-design",1,"https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system","https:\u002F\u002Fgithub.com\u002Fwelflau","2026-11-12 14:55:20",{"source":8,"skillName":5,"commands":67,"prompt":77,"zipAvailable":78},[68,71,74],{"tool":69,"command":70},"npx","npx skills add welflau\u002Fai-dev-system --skill api-design",{"tool":72,"command":73},"bunx","bunx skills add welflau\u002Fai-dev-system --skill api-design",{"tool":75,"command":76},"pnpm","pnpm dlx skills add welflau\u002Fai-dev-system --skill api-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fconfig_packs\u002Fweb-dev\u002Fshared\u002Fskills\u002Fapi-design\u002FSKILL.md",true,[80],{"path":81,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":84,"sourceHtmlUrl":85},"agents\u002Fopenai.yaml","REFERENCE","参考文档",265,"https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fconfig_packs\u002Fweb-dev\u002Fshared\u002Fskills\u002Fapi-design\u002Fagents\u002Fopenai.yaml",[87,119,148,174,197,222],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":92,"sourceHtmlUrl":93,"categories":94,"keywords":101,"publishedAt":118},"01M6HS9Z4B0YA8CJCS2Y2F04Y3","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fwebapp-testing\u002FSKILL.md",[95,98],{"categoryNo":96,"categoryName":97,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":99,"categoryName":100,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000009","前端开发",[102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,39],"testing","webapp testing","webapp","frontend","screenshots","playwright","web","debugging","toolkit","browser","ui","logs","applications","behavior","local","with","2026-11-11 15:11:14",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":123,"sourceHtmlUrl":124,"categories":125,"keywords":129,"publishedAt":118},"01M6HRAGMG7JF0HXYHMA5QHS8A","internal-comms","A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Finternal-comms\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Finternal-comms\u002FSKILL.md",[126],{"categoryNo":127,"categoryName":128,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000005","邮件与沟通",[130,131,53,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147],"internal comms","comms","help","SET","write","use","reports","me","incident","leadership","project","resources","communications","internal communications","formats","sort","my","updates",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":152,"sourceHtmlUrl":153,"categories":154,"keywords":156,"publishedAt":54},"01M6HSTDP4M3JFXEBK91VFB4PA","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Fweb-artifacts-builder\u002FSKILL.md",[155],{"categoryNo":99,"categoryName":100,"taxonomyType":20,"taxonomyTypeDesc":21},[157,108,158,159,160,105,161,162,163,164,165,166,167,168,135,169,170,171,172,39,173],"web artifacts builder","artifacts","artifacts builder","builder","css","components","react","routing","state management","state","file","Tailwind","single-file","simple","ui components","multi","single",{"skillNo":175,"name":176,"nameZh":6,"description":177,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":178,"sourceHtmlUrl":179,"categories":180,"keywords":184,"publishedAt":54},"01M6HSDXH0JSP8R3QTNY9XZ8HN","frontend-design","Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML\u002FCSS layouts, or when styling\u002Fbeautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Ffrontend-design\u002FSKILL.md",[181,182,183],{"categoryNo":99,"categoryName":100,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":31,"categoryName":32,"taxonomyType":28,"taxonomyTypeDesc":29},[105,36,185,161,108,162,163,186,187,188,158,189,114,190,135,191,192,193,194,117,195,196],"frontend design","react components","create","code","examples","landing","ui design","pages","aesthetics","web ui","generic","when",{"skillNo":198,"name":199,"nameZh":6,"description":200,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":201,"sourceHtmlUrl":202,"categories":203,"keywords":205,"publishedAt":54},"01M6HSA77QYVP7A72HREGTDN2C","algorithmic-art","Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists' work to avoid copyright violations.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Falgorithmic-art\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Falgorithmic-art\u002FSKILL.md",[204],{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},[206,207,208,187,188,209,210,211,212,135,213,214,215,216,117,217,218,219,220,221,196],"algorithmic art","Art","algorithmic","flow","js","work","interactive","generative art","exploration","systems","users","Existing","request","generative","copyright","fields",{"skillNo":223,"name":224,"nameZh":6,"description":225,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":226,"sourceHtmlUrl":227,"categories":228,"keywords":230,"publishedAt":54},"01M6HS9HE0X390Y6RQKTY1YNGJ","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Ftheme-factory\u002FSKILL.md",[229],{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},[231,232,233,234,110,235,158,133,236,237,190,238,239,192,240,117,241,242,243,39,244,245],"theme factory","factory","theme","docs","generate","fly","slides","styling","artifact","themes","you","fonts","can","apply","new"]