[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CSDZ1JSHZ552965NVC8G73":3,"skill-same:01M7CSDZ1JSHZ552965NVC8G73":52},{"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":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7CSDZ1JSHZ552965NVC8G73","api-design",null,"REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs.","Henrique1601\u002FSkiilsToIAs","Henrique1601","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F92006691?v=4","01M7CRXVT0GVXVK80JT1GR687S","Henrique Bezerra Dos Santos","01M7CRXVTN5Y8TMWJ1MDSKCQ1T",0,"MIT","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fapi-design\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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","a73152352c0612252131e5cf84e91312a6cf17dc","backend-database\u002Fapi-design","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs","https:\u002F\u002Fgithub.com\u002FHenrique1601","https:\u002F\u002Fbezerraportifolio.netlify.app\u002F","Full Stack Developer | React, Next.js, TypeScript, Node.js & IA | Construindo produtos digitais e soluções SaaS","2026-11-15 02:56:04",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add Henrique1601\u002FSkiilsToIAs --skill api-design",{"tool":38,"command":39},"bunx","bunx skills add Henrique1601\u002FSkiilsToIAs --skill api-design",{"tool":41,"command":42},"pnpm","pnpm dlx skills add Henrique1601\u002FSkiilsToIAs --skill api-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fapi-design\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"agents\u002Fopenai.yaml","REFERENCE","参考文档",265,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fapi-design\u002Fagents\u002Fopenai.yaml",[53,60,67,75,82,89],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7E2ANBW9V6AVX5JXNCEAWF8","rag-architect-agent","Agente Arquiteto de RAG, Embeddings & Busca Vetorial. Especialista em design e implementação de pipelines de Retrieval-Augmented Generation de alta fidelidade: chunking semântico, modelagem pgvector no PostgreSQL (Neon\u002FSupabase), busca híbrida (cosseno + BM25), reranking, validação via TypeSafe AI e filosofia Ponytail (anti-overengineering).","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fcustom-agents\u002Frag-architect-agent\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7E29KKF8R02ZRGYE2MJM67G","rag-architecture-patterns","Padrões arquiteturais e implementação de pipelines RAG (Retrieval-Augmented Generation) de alta fidelidade para qualquer projeto ou sistema. Cobre chunking semântico, embeddings, busca híbrida (pgvector + BM25), reranking, validação via TypeSafe AI e filosofia Ponytail (anti-overengineering).","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fai-agents\u002Frag-architecture-patterns\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":71,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7CWRA8E3BJ7CPY8N8EG28J1","skill-repair","Use this to fix and re-install agent skills that have failed installation.\nThis skill provides the necessary context and permissions to surgically update\nthe `manifest.json` after a fix has been applied.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fskill-repair\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7CWR66FZP8FA47WVZ4Z2EXC","security-scan","Scan your Claude Code configuration (.claude\u002F directory) for security vulnerabilities, misconfigurations, and injection risks using AgentShield. Checks CLAUDE.md, settings.json, MCP servers, hooks, and agent definitions.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-scan\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7CWR0QPY58QPTR1P759TFNG","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-review\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7CWQXCE40XWT4FZ3VWZFGDP","security-bounty-hunter","Hunt for exploitable, bounty-worthy security issues in repositories. Focuses on remotely reachable vulnerabilities that qualify for real reports instead of noisy local-only findings.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-bounty-hunter\u002FSKILL.md",[],[]]