build-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Backend API Development Workflow

后端API开发工作流

Build backend API endpoints, services, and database changes following NestJS patterns, Prisma schema design, and the project's clean architecture conventions.
[!CAUTION] Scope boundary: This skill implements backend code and commits it. It does NOT create pull requests, push to remote, run code reviews, or submit anything for merge. When implementation and commits are complete, stop and suggest the user run
/review-code
next.
遵循NestJS模式、Prisma架构设计以及项目的整洁架构规范,构建后端API端点、服务和数据库变更。
[!CAUTION] 范围边界:本技能仅负责实现后端代码并提交。它不会创建拉取请求、推送到远程仓库、执行代码评审或提交任何内容用于合并。当实现和提交完成后,请停止操作并建议用户下一步运行
/review-code

Step 1: Define API Requirements

步骤1:定义API需求

Ensure we are on a feature branch based on the latest
main
. Always fetch first:
bash
git fetch origin main
If on
main
, create a new feature branch from the latest
origin/main
:
bash
git checkout -b feature/<feature-slug> origin/main
If already on an existing feature branch, rebase it onto the latest
origin/main
to pick up any changes:
bash
git status --porcelain
If the working tree is dirty, stash changes before rebasing:
bash
git stash push -m "build-api: stash before rebase"
git rebase origin/main
git stash pop
If the working tree is clean, rebase directly:
bash
git rebase origin/main
If the user provides a GitHub issue number (e.g.,
/build-api 42
or
/build-api #42
), fetch the issue and signal work is in progress (see AGENTS.md "Label Management" for rules):
bash
gh issue view <number> --json title,body,labels,state,number
确保我们处于基于最新
main
分支的功能分支上。请先执行拉取操作:
bash
git fetch origin main
如果当前在
main
分支上,从最新的
origin/main
创建新的功能分支:
bash
git checkout -b feature/<feature-slug> origin/main
如果已经在现有功能分支上,将其变基到最新的
origin/main
以获取所有变更:
bash
git status --porcelain
如果工作区有未提交的变更,在变基前先暂存:
bash
git stash push -m "build-api: stash before rebase"
git rebase origin/main
git stash pop
如果工作区是干净的,直接执行变基:
bash
git rebase origin/main
如果用户提供了GitHub issue编号(例如
/build-api 42
/build-api #42
),获取该issue并标记为进行中(请参阅AGENTS.md中的「标签管理」规则):
bash
gh issue view <number> --json title,body,labels,state,number

Single-developer constraint: only one issue should be in-progress at a time.

单开发者约束:同一时间只能有一个issue处于进行中状态。

First, remove in-progress from any other issue that has it:

首先,移除其他所有处于进行中状态的issue的该标签:

gh issue list --label "in-progress" --state open --json number --jq '.[].number' | while read n; do gh issue edit "$n" --remove-label "in-progress" done
gh issue edit <number> --add-label "in-progress"

Verify the issue is tracked on the [Product Roadmap]({PROJECT_BOARD_URL}) project board. If not, add it:

```bash
gh issue list --label "in-progress" --state open --json number --jq '.[].number' | while read n; do gh issue edit "$n" --remove-label "in-progress" done
gh issue edit <number> --add-label "in-progress"

验证该issue是否已添加到[产品路线图]({PROJECT_BOARD_URL})项目看板中。如果没有,将其添加:

```bash

--limit 200 covers the current board size; increase if the project grows beyond 200 items

--limit 200覆盖当前看板的容量;如果项目规模超过200个项,请增加该值

EXISTING=$(gh project item-list {PROJECT_NUMBER} --owner {OWNER} --format json --limit 200
| python3 -c " import json, sys data = json.load(sys.stdin) for item in data.get('items', []): # <number> must be an integer literal, e.g., == 42, not == '42' if item.get('content', {}).get('number') == <number>: print(item['id']) break ")
if [ -z "$EXISTING" ]; then ITEM_ID=$(gh project item-add {PROJECT_NUMBER} --owner {OWNER} --url "https://github.com/{OWNER}/{REPO}/issues/<number>" --format json | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])") echo "Warning: Issue #<number> was not on the project board. Added it now (item $ITEM_ID)." fi

> [!WARNING]
> If the issue was missing from the project board, it may also be missing phase, size, and date fields. Check the project item and warn the user if fields are unset — this suggests the issue was created outside of `/plan-feature` or `/security-audit`, which are the skills that ensure board membership and field population.

Ask the user (or read from the decision record / issue body if `/plan-feature` was run first):

- What resource(s) or endpoint(s) are being created or modified?
- What operations are needed (CRUD, custom actions, queries)?
- Are there database schema changes?
- Is this a tRPC procedure or REST endpoint?
- Are there authentication or authorization requirements?

If a decision record exists in `docs/decisions/`, read it for the task breakdown.
EXISTING=$(gh project item-list {PROJECT_NUMBER} --owner {OWNER} --format json --limit 200
| python3 -c " import json, sys data = json.load(sys.stdin) for item in data.get('items', []): # <number>必须是整数字面量,例如== 42,而非== '42' if item.get('content', {}).get('number') == <number>: print(item['id']) break ")
if [ -z "$EXISTING" ]; then ITEM_ID=$(gh project item-add {PROJECT_NUMBER} --owner {OWNER} --url "https://github.com/{OWNER}/{REPO}/issues/<number>" --format json | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])") echo "Warning: Issue #<number> was not on the project board. Added it now (item $ITEM_ID)." fi

> [!WARNING]
> 如果该issue未在项目看板中,它可能还缺少阶段、规模和日期字段。请检查项目项,如果字段未设置,请向用户发出警告——这表明该issue是通过`/plan-feature`或`/security-audit`之外的方式创建的,而这两个技能会确保issue被添加到看板并填充相关字段。

向用户询问(如果已运行`/plan-feature`,则从决策记录或issue正文中读取):

- 要创建或修改哪些资源/端点?
- 需要哪些操作(CRUD、自定义动作、查询)?
- 是否需要变更数据库架构?
- 这是tRPC过程还是REST端点?
- 是否有认证或授权要求?

如果`docs/decisions/`目录下存在决策记录,请阅读其中的任务分解内容。

Step 2: Design API Contract

步骤2:设计API契约

Invoke
/backend-development:api-design-principles
for API design guidance.
Design the full API contract:
  • Endpoint paths and HTTP methods (REST) or procedure names (tRPC)
  • Request types: Full TypeScript interfaces with all fields, optional/required markers
  • Response types: Success responses, error responses, pagination if applicable
  • Validation rules: Using Zod schemas for runtime validation
  • Error format: Standardized error response structure
  • Auth requirements: Which endpoints need authentication, role-based access
If this represents a significant API decision (new resource type, breaking change to existing API, new architectural pattern), activate the Architecture Council using
.claude/councils/architecture-council.md
:
Model Selection: See the Model Selection section in README.md for mapping agent model specs to Task tool parameters.
调用
/backend-development:api-design-principles
获取API设计指导。
设计完整的API契约:
  • 端点路径和HTTP方法(REST)或过程名称(tRPC)
  • 请求类型:包含所有字段的完整TypeScript接口,标记可选/必填字段
  • 响应类型:成功响应、错误响应,如有需要包含分页
  • 验证规则:使用Zod schema进行运行时验证
  • 错误格式:标准化的错误响应结构
  • 认证要求:哪些端点需要认证、基于角色的访问控制
如果这是一项重大API决策(新资源类型、对现有API的破坏性变更、新架构模式),请使用
.claude/councils/architecture-council.md
启动架构委员会审核:
模型选择:请参阅README.md中的模型选择部分,了解代理模型规格与Task工具参数的映射关系。

Principal Engineer — consult: full-stack-orchestration

首席工程师 — 咨询:full-stack-orchestration

  • Vote: Approve / Concern / Block
  • Rationale: Architectural soundness, scalability, maintainability
  • Recommendations: Patterns to follow, trade-offs to consider
  • 投票:批准 / 关注 / 阻止
  • 理由:架构合理性、可扩展性、可维护性
  • 建议:应遵循的模式、需要考虑的权衡

Platform Engineer — consult: cloud-infrastructure

平台工程师 — 咨询:cloud-infrastructure

  • Vote: Approve / Concern / Block
  • Rationale: Operational implications, deployment considerations
  • Recommendations: Infrastructure concerns, monitoring needs
  • 投票:批准 / 关注 / 阻止
  • 理由:运维影响、部署考量
  • 建议:基础设施注意事项、监控需求

Security Engineer — consult: security-scanning

安全工程师 — 咨询:security-scanning

  • Vote: Approve / Concern / Block
  • Rationale: Security risks, attack surface, compliance
  • Recommendations: Security hardening steps, input validation
  • 投票:批准 / 关注 / 阻止
  • 理由:安全风险、攻击面、合规性
  • 建议:安全加固步骤、输入验证

Backend Specialist — consult: backend-development

后端专家 — 咨询:backend-development

  • Vote: Approve / Concern / Block
  • Rationale: API design quality, NestJS patterns, developer experience
  • Recommendations: Implementation approach, ecosystem integration
  • 投票:批准 / 关注 / 阻止
  • 理由:API设计质量、NestJS模式、开发者体验
  • 建议:实现方法、生态系统集成

CHECKPOINT: Present the API contract (and Architecture Council evaluation if activated) to the user. Wait for approval before implementation begins.

检查点:向用户展示API契约(以及如果启动了架构委员会审核,需包含其评估结果)。在开始实现前等待用户批准。

Step 3: Database Layer (if needed)

步骤3:数据库层(如有需要)

If schema changes are required:
  1. Invoke
    /database-design:postgresql
    for PostgreSQL schema design guidance
  2. Design the Prisma schema changes:
    • Model definitions with proper field types
    • Relations and foreign keys
    • Indexes for query performance
    • Unique constraints and validations
    • Enums where appropriate
  3. Invoke
    /database-migrations:sql-migrations
    for migration generation guidance
如果需要变更架构:
  1. 调用
    /database-design:postgresql
    获取PostgreSQL架构设计指导
  2. 设计Prisma架构变更:
    • 包含适当字段类型的模型定义
    • 关联关系和外键
    • 用于查询性能的索引
    • 唯一约束和验证
    • 合理使用枚举类型
  3. 调用
    /database-migrations:sql-migrations
    获取迁移生成指导

CHECKPOINT: Present the Prisma schema changes and migration plan to the user. Wait for approval before running the migration.

检查点:向用户展示Prisma架构变更和迁移计划。在运行迁移前等待用户批准。

  1. Generate and apply the migration:
    bash
    pnpm db:migrate
  2. If seed data is needed, update the seed script.
  1. 生成并应用迁移:
    bash
    pnpm db:migrate
  2. 如果需要种子数据,更新种子脚本。

Step 4: Implement Backend

步骤4:实现后端

Follow NestJS patterns and
/backend-development:architecture-patterns
for clean architecture:
遵循NestJS模式和
/backend-development:architecture-patterns
的整洁架构要求:

Types and DTOs

类型和DTO

  • Define request/response TypeScript interfaces
  • Create Zod validation schemas for runtime validation
  • Export types for frontend consumption (via tRPC or shared packages)
  • 定义请求/响应TypeScript接口
  • 创建用于运行时验证的Zod schema
  • 导出供前端使用的类型(通过tRPC或共享包)

Repository / Data Access Layer

仓库/数据访问层

  • Create or update Prisma queries
  • Implement data access patterns (repository pattern if used)
  • Add query optimization (select specific fields, use includes wisely)
  • 创建或更新Prisma查询
  • 实现数据访问模式(如使用仓库模式)
  • 添加查询优化(选择特定字段、合理使用includes)

Service Layer

服务层

  • Implement business logic in NestJS services
  • Add input validation and business rule enforcement
  • Handle error cases with typed exceptions
  • Keep services testable (inject dependencies)
  • 在NestJS服务中实现业务逻辑
  • 添加输入验证和业务规则强制执行
  • 使用类型化异常处理错误场景
  • 保持服务的可测试性(注入依赖)

Controller / Router Layer

控制器/路由层

  • Create tRPC procedures or NestJS controllers
  • Wire up validation, auth guards, and services
  • Implement proper HTTP status codes (REST) or error codes (tRPC)
  • Add rate limiting if needed for public endpoints
  • 创建tRPC过程或NestJS控制器
  • 连接验证、认证守卫和服务
  • 实现正确的HTTP状态码(REST)或错误码(tRPC)
  • 如有需要,为公共端点添加限流

Guards and Middleware

守卫和中间件

  • Add authentication guards where required
  • Add authorization checks (role-based or resource-based)
  • Add request logging for debugging
Use
/javascript-typescript:typescript-advanced-types
for complex type scenarios (generics, conditional types, mapped types).
For performance-sensitive endpoints, invoke
/application-performance:performance-optimization
for API profiling and optimization patterns.
  • 在需要的地方添加认证守卫
  • 添加授权检查(基于角色或基于资源)
  • 添加请求日志用于调试
对于复杂类型场景,调用
/javascript-typescript:typescript-advanced-types
获取指导(泛型、条件类型、映射类型)。
对于性能敏感的端点,调用
/application-performance:performance-optimization
获取API分析和优化模式指导。

Step 5: Write Tests

步骤5:编写测试

Following the QA Lead testing strategy:
遵循QA负责人的测试策略:

Unit Tests

单元测试

  • Test each service method in isolation
  • Mock Prisma client and external dependencies
  • Test business logic, validation rules, error handling
  • Cover happy paths and edge cases
  • 独立测试每个服务方法
  • 模拟Prisma客户端和外部依赖
  • 测试业务逻辑、验证规则、错误处理
  • 覆盖正常路径和边缘情况

Integration Tests

集成测试

  • Test endpoints against a real (test) database
  • Verify request validation rejects bad input
  • Verify authentication and authorization enforcement
  • Test error responses for various failure modes
  • 针对真实(测试)数据库测试端点
  • 验证请求验证是否拒绝无效输入
  • 验证认证和授权的强制执行
  • 测试各种失败模式下的错误响应

Validation Tests

验证测试

  • Boundary conditions (empty strings, max lengths, special characters)
  • Invalid input formats
  • Missing required fields
  • Type coercion and casting
Run tests and verify coverage:
bash
pnpm test
Ensure coverage meets the >80% target.
  • 边界条件(空字符串、最大长度、特殊字符)
  • 无效输入格式
  • 缺失必填字段
  • 类型转换和强制转换
运行测试并验证覆盖率:
bash
pnpm test
确保覆盖率达到>80%的目标。

Step 6: Generate API Documentation

步骤6:生成API文档

Invoke
/documentation-generation:openapi-spec-generation
to generate or update API documentation for the new endpoints.
If using tRPC, document the procedure signatures and usage examples. If using REST, generate or update the OpenAPI/Swagger specification.
调用
/documentation-generation:openapi-spec-generation
生成或更新新端点的API文档。
如果使用tRPC,请记录过程签名和使用示例。 如果使用REST,请生成或更新OpenAPI/Swagger规范。

Step 7: Self-Review

步骤7:自审

Before presenting to the user, verify:
bash
pnpm type-check      # No TypeScript errors
pnpm lint            # No linting violations
pnpm format:check    # No Prettier formatting issues
pnpm test            # All unit tests pass
pnpm test:smoke      # DI container and HTTP pipeline boot OK
If
format:check
fails, run
pnpm exec prettier --write
on the reported files before proceeding.
Check for common issues:
  • No hardcoded secrets or credentials
  • Proper error handling (no swallowed errors)
  • Input validation on all external-facing endpoints
  • Proper use of TypeScript strict mode (no
    any
    types)
在向用户展示前,验证以下内容:
bash
pnpm type-check      # 无TypeScript错误
pnpm lint            # 无代码规范违规
pnpm format:check    # 无Prettier格式问题
pnpm test            # 所有单元测试通过
pnpm test:smoke      # DI容器和HTTP管道启动正常
如果
format:check
失败,请先对报告的文件运行
pnpm exec prettier --write
,然后再继续。
检查常见问题:
  • 没有硬编码的密钥或凭证
  • 正确的错误处理(没有吞掉错误)
  • 所有外部端点都有输入验证
  • 正确使用TypeScript严格模式(无
    any
    类型)

Step 8: Update Documentation

步骤8:更新文档

If this API change alters how the project is set up, built, or run, update the relevant documentation before committing:
  1. README.md — Update Quick Start, Running the Application, or Project Structure sections if the change introduces new infrastructure, services, environment variables, or commands
  2. docs/DEVELOPMENT.md — Update Prerequisites, Local Development Setup, Database Operations, or Troubleshooting sections as needed
  3. Makefile — Add new targets for common operations (e.g., new Docker services, database commands)
  4. .env.example
    files
    — Add new environment variables with clear descriptions and safe defaults
  5. docs/INDEX.md
    — If any new files were added to
    docs/
    , add them to the appropriate table in the master documentation index
[!IMPORTANT] A developer cloning the repo fresh must be able to get the project running by following README.md alone. If your API change adds a Docker service, database, new environment variable, or external dependency, the docs MUST reflect it.
如果此API变更影响项目的设置、构建或运行方式,请在提交前更新相关文档:
  1. README.md — 如果变更引入了新的基础设施、服务、环境变量或命令,请更新「快速开始」、「运行应用」或「项目结构」部分
  2. docs/DEVELOPMENT.md — 根据需要更新「前提条件」、「本地开发设置」、「数据库操作」或「故障排除」部分
  3. Makefile — 为常见操作添加新的目标(例如新的Docker服务、数据库命令)
  4. .env.example
    文件
    — 添加新的环境变量,包含清晰的描述和安全的默认值
  5. docs/INDEX.md
    — 如果
    docs/
    目录下添加了新文件,请将其添加到主文档索引的相应表格中
[!IMPORTANT] 新克隆仓库的开发者必须能够仅遵循README.md的说明就能运行项目。如果你的API变更添加了Docker服务、数据库、新环境变量或外部依赖,文档必须相应更新。

Step 9: Commit

步骤9:提交

CHECKPOINT: Present a summary of all changes — files modified, API contract implemented, test results, and documentation. Wait for user approval.

检查点:向用户展示所有变更的摘要——修改的文件、实现的API契约、测试结果和文档。等待用户批准。

Commit with conventional commit format:
feat(api): add <resource> endpoints
Or if modifying existing endpoints:
feat(api): update <resource> with <change-description>
使用约定式提交格式进行提交:
feat(api): add <resource> endpoints
如果是修改现有端点:
feat(api): update <resource> with <change-description>

Update GitHub Issue

更新GitHub Issue

If implementation was initiated from a GitHub issue:
  1. Comment on it with progress:
    bash
    gh issue comment <number> --body "Implementation committed on branch \`<branch-name>\`. Proceeding to code review via \`/review-code\`."
[!NOTE] Do not remove the
in-progress
label here. The label stays on the issue until it is closed (handled automatically by
.github/workflows/label-cleanup.yml
). This ensures the issue remains visibly in-progress through code review and PR submission.
如果是从GitHub issue启动的实现:
  1. 在该issue上评论进度:
    bash
    gh issue comment <number> --body "Implementation committed on branch \`<branch-name>\`. Proceeding to code review via \`/review-code\`."
[!NOTE] 不要在此处移除
in-progress
标签。该标签会一直保留到issue被关闭(由
.github/workflows/label-cleanup.yml
自动处理)。这确保在代码评审和PR提交过程中,该issue始终显示为进行中状态。

Step 10: Hand Off — STOP Here

步骤10:移交——到此为止

[!CAUTION] This skill's work is done. Do NOT proceed to create a pull request, push to remote, or run a code review. Those are separate skills with their own workflows and checkpoints.
Present the next step to the user:
  • Recommended: Run
    /review-code
    for multi-perspective security and quality review before submitting
  • If more work remains: Continue with remaining tasks, then run
    /review-code
If working from a GitHub issue, remind the user:
  • The PR should reference the issue with
    Closes #<number>
    so it auto-closes when merged
  • /submit-pr
    will detect related issues from commit messages
Pipeline:
/plan-feature
/build-feature
or
/build-api
/review-code
/submit-pr
Do not push the branch, create a PR, or invoke
/submit-pr
from within this skill.
[!CAUTION] 本技能的工作已完成。请勿继续创建拉取请求、推送到远程仓库或执行代码评审。这些属于独立技能,有各自的工作流和检查点。
向用户展示下一步操作:
  • 推荐:在提交前运行
    /review-code
    进行多视角的安全和质量评审
  • 如果还有更多工作:继续完成剩余任务,然后运行
    /review-code
如果是从GitHub issue开始的工作,提醒用户:
  • PR中应使用
    Closes #<number>
    引用该issue,以便合并时自动关闭
  • /submit-pr
    会从提交消息中检测相关issue
流程
/plan-feature
/build-feature
/build-api
/review-code
/submit-pr
请勿在此技能内推送分支、创建PR或调用
/submit-pr