AgentSkillsCN

api-design

当用户提出“创建 API 端点”“构建 REST API”“添加控制器”“设计 API”“实现 CRUD 操作”“添加校验逻辑”“处理 API 错误”,或任何后端 API 开发相关需求时,可运用此技能。它将提供 REST API 设计模式、响应格式、校验机制以及最佳实践。

SKILL.md
--- frontmatter
name: api-design
description: Use this skill when the user asks to "create an API endpoint", "build a REST API", "add a controller", "design an API", "implement CRUD operations", "add validation", "handle API errors", or any backend API development work. Provides REST API design patterns, response formats, validation, and best practices.

REST API Design (packages/functions)

For security patterns, see security skill

Quick Reference

TopicReference File
Response Helpers, Status Codes, Error Codesreferences/response-format.md
Storefront Endpoints, Shop Resolution, PIIreferences/client-api.md
Yup Schemas, Validation Middlewarereferences/validation.md

CRITICAL: Firebase/Koa Context

javascript
// WRONG - Standard Koa (does NOT work in Firebase)
const data = ctx.request.body;

// CORRECT - Firebase/Koa
const data = ctx.req.body;
PropertyAccess Pattern
Request bodyctx.req.body
Query paramsctx.query
URL paramsctx.params
Response bodyctx.body = {...}

Directory Structure

code
packages/functions/src/
├── routes/              # Route definitions
├── controllers/         # Request handlers
├── middleware/          # Auth, validation
└── validations/         # Yup schemas

RESTful Conventions

ActionMethodRoute
ListGET/resources
Get oneGET/resources/:id
CreatePOST/resources
UpdatePUT/resources/:id
DeleteDELETE/resources/:id
ActionPOST/resources/:id/action

Controller Pattern

javascript
export async function getOne(ctx) {
  try {
    const {shop} = ctx.state;
    const {id} = ctx.params;

    const resource = await repository.getById(shop.id, id);

    if (!resource) {
      ctx.status = 404;
      ctx.body = errorResponse('Not found', 'NOT_FOUND', 404);
      return;
    }

    ctx.body = itemResponse(pick(resource, publicFields));
  } catch (error) {
    console.error('Error:', error);
    ctx.status = 500;
    ctx.body = errorResponse('Server error', 'INTERNAL_ERROR', 500);
  }
}

Pagination (Cursor-Based)

javascript
// Request
GET /api/customers?limit=20&cursor=eyJpZCI6IjEyMyJ9

// Response
{
  "data": [...],
  "meta": {
    "pagination": {
      "hasNext": true,
      "nextCursor": "eyJpZCI6IjE0MyJ9",
      "limit": 20
    }
  }
}

Checklist

code
- Uses response helpers (successResponse/errorResponse)
- Correct HTTP status codes
- Input validated with Yup schema
- Queries scoped by shopId
- Response fields picked (no internal data)
- Error handling with try-catch
- Rate limiting applied
- Authentication middleware