Rest api endpoint builder

From findscripter/everything-skills · View interactive version

Rest api endpoint builder is an AI agent skill from the GitHub repository findscripter/everything-skills. 当需要新建或扩展后端 REST API 端点时使用;按「路由→校验→鉴权→业务→错误处理→响应→文档→测试」分层产出生产级端点代码与规范;不适用于前端调用、GraphQL/gRPC 或纯架构选型;触发词:REST API、端点、路由、CRUD、接口

How to use this skill

Skill file

何时使用

适用:

不该用(负边界):

步骤

每个端点按以下分层逐项产出,缺一不可:

  1. 路由定义:选对 HTTP 方法,挂上鉴权与校验中间件。
  2. 入参校验:处理前先校验 body / params / query,不通过即返回 400。
  3. 鉴权与授权:受保护路由要求登录(401),并校验资源归属(403)。
  4. 业务逻辑:核心处理,注意幂等与并发冲突(409)。
  5. 错误处理:try/catch 局部兜底 + 全局错误中间件,生产环境不泄露细节。
  6. 响应格式化:统一 { success, data } / { error } 结构,列表带 pagination。
  7. API 文档:用 JSDoc 注释标注路由、入参、返回码、示例。
  8. 测试(按需):覆盖正常路径与关键校验失败路径。

指令

路由 + 校验 + 处理函数三段式(Express / Fastify 任选其一):

// Express
router.post('/api/users', authenticate, validateUser, createUser);

// Fastify(用 schema 内建校验)
fastify.post('/api/users', { preHandler: [authenticate], schema: userSchema }, createUser);

入参校验中间件,处理前先拦截非法输入:

const validateUser = (req, res, next) => {
  const { email, name, password } = req.body;
  if (!email || !email.includes('@'))   return res.status(400).json({ error: 'Valid email required' });
  if (!name || name.length < 2)         return res.status(400).json({ error: 'Name must be at least 2 characters' });
  if (!password || password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters' });
  next();
};

处理函数:查重(409) → 加盐哈希密码 → 落库 → 剔除敏感字段 → 返回 201:

const createUser = async (req, res) => {
  try {
    const { email, name, password } = req.body;
    const existing = await db.users.findOne({ email });
    if (existing) return res.status(409).json({ error: 'User already exists' });

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = await db.users.create({ email, name, password: hashedPassword, createdAt: new Date() });

    const { password: _, ...userWithoutPassword } = user; // 永不回传密码
    res.status(201).json({ success: true, data: userWithoutPassword });
  } catch (error) {
    console.error('Create user error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

全局错误中间件,生产环境屏蔽内部细节:

app.use((err, req, res, next) => {
  console.error(err.stack);
  const message = process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message;
  res.status(err.status || 500).json({ error: message });
});

HTTP 状态码约定:

统一响应结构:

// 成功
{ "success": true, "data": { } }
// 错误
{ "error": "Error message", "details": { } }
// 列表带分页
{ "success": true, "data": [], "pagination": { "page": 1, "limit": 20, "total": 100 } }

安全检查清单(上线前逐项确认):

示例

CRUD 路由约定:

POST   /api/resources              创建,Body: { name, description }
GET    /api/resources?page=1&limit=20   列表
GET    /api/resources/:id          查单条
PUT    /api/resources/:id          更新,Body: { name, description }
DELETE /api/resources/:id          删除

分页查询(并发取数据与总数):

const getResources = async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 20;
  const skip = (page - 1) * limit;
  const [resources, total] = await Promise.all([
    db.resources.find().skip(skip).limit(limit),
    db.resources.countDocuments()
  ]);
  res.json({ success: true, data: resources,
    pagination: { page, limit, total, pages: Math.ceil(total / limit) } });
};

过滤与排序:

const { status, sort = '-createdAt' } = req.query;
const filter = {};
if (status) filter.status = status;
const resources = await db.resources.find(filter).sort(sort).limit(20);

测试(覆盖成功 + 校验失败两条路径):

describe('POST /api/users', () => {
  it('creates a user', async () => {
    const res = await request(app).post('/api/users')
      .send({ email: 'test@example.com', name: 'Test User', password: 'password123' });
    expect(res.status).toBe(201);
    expect(res.body.success).toBe(true);
    expect(res.body.data.password).toBeUndefined(); // 不回传密码
  });
  it('rejects invalid email', async () => {
    const res = await request(app).post('/api/users')
      .send({ email: 'invalid', name: 'Test User', password: 'password123' });
    expect(res.status).toBe(400);
    expect(res.body.error).toContain('email');
  });
});

文档注释模板:

/**
 * @route POST /api/users
 * @desc 创建新用户
 * @access Public
 * @body {string} email    用户邮箱(必填)
 * @body {string} name     用户名(必填)
 * @body {string} password 密码,至少 8 位(必填)
 * @returns {201} 创建成功 / {400} 校验失败 / {409} 已存在 / {500} 服务端错误
 */

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT 许可证)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.