SuperAPI AI Directory

build-backend-api-design

Coding & development

View repository

Updated 10-16 09:44

About this skill

API Design — REST/HTTP Interface Contract Design

This Skill is not responsible for writing API implementations, but for freezing the API contract before implementation: resources, endpoints, DTOs, errors, permissions, pagination, idempotency, concurrency, compatibility, and contract tests.

Entry/Exit

  • Entry: A new API endpoint needs to be defined, an existing endpoint contract needs to be modified, or a cross-service HTTP contract needs to be designed
  • Exit:
    • API endpoint list (method + path + authentication + permissions)
    • Request / Response DTO
    • Error Code list
    • Permission and authentication rules
    • Pagination / sorting / filtering rules
    • Idempotency and concurrency control rules
    • Zod / TypeScript / OpenAPI schema
    • Minimum Contract Tests coverage
  • Points to: Once the interface is stable, proceed to implementation (build-workflow-execute)
  • Preload: CANON.md + build-quality-tdd/SKILL.md

When Not to Use

  • Only implementing an existing API, without changing requests/responses, error semantics, or module boundaries
  • Only fixing an internal API bug, with externally observable behavior unchanged
  • Only optimizing query performance, without changing endpoints, fields, error semantics, or pagination semantics
  • Only supplementing API documentation, without needing to redesign the contract
  • Pure internal refactoring, with no change to the contract observable by callers
  • Database schema or query design is the main problem (use build-backend-database)
  • When GraphQL schema design is the main problem, use a dedicated GraphQL Skill
  • When Webhook / Event / Message Queue contracts are the main problem, use an event contract Skill

Core Anchor Points

Hyrum's Law

All observable behavior may become a de facto contract. Field types, null semantics, default values, error codes, HTTP status, sorting, and pagination structure are all treated as contracts.

Execution rule: Assume during design that every behavior is permanent. When judging whether a change is compatible, do not look at whether the server can run; only look at whether old clients can still work correctly without modification.

Contract-first / Schema-first

First define Method + Path + Request + Response + Error + Auth + Pagination + Schema, then proceed to implementation.

Execution rule: API design order—resource → endpoint → Request DTO → Response DTO → Error Codes → permissions → pagination/sorting/filtering → idempotency/concurrency → schema → contract tests → then proceed to implementation.

RFC 9110 / RFC 5789

Follow HTTP method semantics. By default, model with resource nouns, and do not put CRUD verbs in URL paths.

Execution rule:

  • GET queries, POST creates/actions, PUT full updates, PATCH partial updates, DELETE deletes
  • Operation endpoints (POST /tasks/:id/complete) are used only when the action has a clear business meaning, triggers complex side effects, and its error semantics and idempotency have been defined
  • Ordinary state updates prefer PATCH /tasks/:id { "status": "completed" }

RFC 9457 / Problem Details

Error responses must be unified, stable, and machine-readable.

Execution rule:

  • Format:{ error: { code, message, details, requestId } }
  • code: uppercase snake_case, stable and unchanging, such as TASK_TITLE_REQUIRED、IDEMPOTENCY_KEY_CONFLICT
  • message: for humans, localizable, not used as a basis for program judgment
  • requestId: used for troubleshooting and trace tracking
  • 400 vs 422 is subject to project convention; the key is project-wide consistency

DTO / Clean Architecture

DB Model is an internal implementation; API Output is an external contract.

Execution rules:

  • Responses must be converted through an Output DTO / mapper whitelist and must not directly return the db model.
  • Forbidden to expose: passwordHash, internalNotes, deletedAt, tenantInternalId, token, secret, audit-only fields
  • Output fields are not "whatever the database has is what gets returned", but rather "only what the caller needs to complete the task is what gets returned".

DDD Domain Invariants

API boundary validates format; Service / Domain protects business rules and invariants.

Execution rules:

  • API boundary: request body shape, query/params, headers, required fields, type validation
  • Service / Domain: permissions, resource state, business invariants, tenant isolation, duplicate submissions
  • Adapter boundary: external service return shape, database query result shape
  • One-sentence principle:The boundary validates format; the domain protects rules.

Backward Compatibility

Prioritize compatible extensions and avoid breaking changes.

Execution rules: Follow the compatibility matrix—adding optional fields is usually safe; changing field types/semantics, deleting fields, adding required fields, and changing default sorting/default values/error formats are usually breaking. Versioning is a last resort, not the default approach.

Idempotency-Key

POST requests with side effects that may be retried must evaluate idempotency.

Execution rules: Recommended Idempotency-Key header. Same key + same body → return the first result; same key + different body → 409 Conflict IDEMPOTENCY_KEY_CONFLICT。

Optimistic Locking

PATCH / PUT requests that may be updated concurrently must evaluate version / ETag / If-Match.

Execution rules: Whether version goes in the body or the If-Match header depends on project style, but one must be chosen explicitly. Version conflicts return 409 TASK_VERSION_CONFLICT。

Cursor / Page Pagination

List endpoints must be paginated and must define default sorting.

Execution rules:

  • Admin management lists → page/pageSize; large data/feed/real-time changing → cursor/limit
  • By default, sort by createdAt desc or id desc
  • Support sorting by whitelisted fields; arbitrary fields must not be passed through directly to the database.
  • total / totalPages is optional (calculating total may be expensive)

Schema / Runtime Validation

TypeScript interface only provides compile-time constraints. API boundaries must use runtime schema (Zod / Valibot / TypeBox / JSON Schema / OpenAPI).

Execution rules: Requests are validated using schema; OpenAPI is generated from schema or kept in sync.Do not just write an interface and then directly trust req.body.

Basic type specifications

  • Time: ISO 8601 string; do not use Date objects in DTOs
  • ID: string; do not expose the database auto-increment strategy
  • Amount: integer in the smallest currency unit or decimal string; do not use float

Authentication and authorization

Each endpoint must specify: whether authentication is required, roles/permissions, resource-level permissions, tenant isolation, and whether unauthorized access returns 403 or 404.

  • 401: no authentication or invalid credentials
  • 403: authenticated but unauthorized
  • 404: the resource does not exist, or resource existence is not exposed for security (private documents, multi-tenant resources, user private data)

API Review process

When designing an API, self-check in order: Resource → Contract → Compatibility → Security → Reliability → Test.

Common arguments

Claim Reality Consequence
"Right now we only have one consumer" Hyrum's Law. With 1 consumer it's easiest to get it right. When new consumers integrate, the interface needs refactoring
"Error format doesn't matter" Inconsistency = each consumer needs a different parser. n endpoints × m formats = n×m parsers
"We'll add pagination later" A list endpoint without pagination will blow up on some Friday. After data grows, the service crashes and times out
"If v2 is incompatible, deprecate it" Extension is better than versioning; two versions = double maintenance. Double the tests + double the bugs + migration cost
"If POST retries, just retry" Client retries are normal behavior in a network environment. Duplicate orders / duplicate charges
"Concurrent updates are rare" Double-clicks, retries, and mobile network switching all trigger them. Lost updates from overwrites

Red flag — STOP

  • Starting implementation without defining the contract first
  • Defining only success responses, with no error responses
  • Inconsistent error formats across endpoints
  • error.message is used by clients as the basis for decisions
  • URL paths contain CRUD verbs (/createTask、/getTasks)
  • Ordinary state updates are designed as action endpoints
  • Lists have no pagination or default ordering
  • Large data/feed lists use page/pageSize, causing performance or consistency issues
  • POST has side effects but no idempotency strategy
  • PATCH / PUT have no concurrency control
  • DB models are returned directly
  • API output has no whitelist mapper
  • Exposing internal fields such as passwordHash, token, internalNotes
  • Adding new required request fields
  • Changing the type or semantics of existing fields
  • Adding enum values without evaluating old clients
  • Unclear 403 / 404 policy when permission fails
  • Writing only TypeScript interfaces, with no runtime schema
  • Moving into implementation without contract tests

Validation failure handling

Validation item Failure manifestation Handling approach
Contract not defined before implementation Writing code first, then defining types Stop implementation, first define the schema and DTO
No error code Only returning message Add a stable error.code; message is only for humans
Inconsistent error format Different error structures across endpoints Unify as { error: { code, message, details, requestId } }
No pagination Lists return all data Add pagination parameters and a PaginatedResponse wrapper
No default ordering Pagination result order is unstable Add fixed ordering fields
No idempotency strategy POST retries create duplicates Add Idempotency-Key
No concurrency control PATCHes overwrite each other Add version / If-Match
DB model exposed directly Return internal fields Define Output DTO and mapper
No permission description Only write authenticated Explicitly define role, permission, ownership
No schema Only interface Add Zod / OpenAPI schema
Modify existing fields Change type or semantics Stop, switch to adding new fields or a versioning strategy

Output template

API 设计完成:

资源模型:
  - Task: 用户任务资源
  - Comment: 任务评论子资源

端点列表:
  - GET    /tasks              → GetTasksQuery → PagePaginatedResponse<TaskOutput>
  - POST   /tasks              → CreateTaskRequest → TaskOutput
  - GET    /tasks/:id          → TaskOutput
  - PATCH  /tasks/:id          → PatchTaskRequest → TaskOutput
  - DELETE /tasks/:id          → 204
  - GET    /tasks/:id/comments → CursorPaginatedResponse<CommentOutput>

权限规则:
  - 所有端点需要 authenticated
  - GET /tasks/:id 需要 task:read + tenant ownership
  - PATCH /tasks/:id 需要 task:write + tenant ownership
  - 无权限是否返回 403/404: 私有资源返回 404

错误格式:
  { error: { code, message, details, requestId } }

错误 code:
  - TASK_TITLE_REQUIRED / TASK_NOT_FOUND / TASK_PERMISSION_DENIED
  - TASK_VERSION_CONFLICT / IDEMPOTENCY_KEY_CONFLICT

命名规范:
  - URL path: plural resource names
  - JSON body: camelCase
  - TypeScript: camelCase
  - Error code: UPPER_SNAKE_CASE

分页: 管理列表 page/pageSize,Feed/大数据 cursor/limit,必须有默认排序
幂等性: 有副作用的 POST 支持 Idempotency-Key,冲突返回 409
并发控制: PATCH/PUT 使用 version 或 If-Match,冲突返回 409
输入/输出分离: Output DTO + mapper 白名单,不暴露 DB model
Schema: src/schemas/task.schema.ts + src/types/api.ts + openapi.yaml
合约测试: tests/api-contracts/tasks.contract.test.ts

Done When:
  - endpoint、DTO、schema、错误 code、权限、分页、幂等、并发控制、contract tests 全部定义完成
  - 未进入业务实现

Verification checklist

Contract Checklist

  • Every endpoint has method + path
  • Every endpoint has Request DTO and Response DTO
  • Every endpoint defines success and error status codes
  • Every error has a stable error.code
  • All error responses use a unified format
  • Every endpoint defines authentication and permission requirements
  • Every list endpoint has pagination and default sorting
  • Idempotency has been evaluated for creation-type POST
  • Concurrency control has been evaluated for PATCH / PUT
  • API DTO is separated from DB model
  • Schema can be validated at runtime
  • Contract tests cover success and failure paths

Compatibility Checklist

  • No response fields have been removed or field types/semantics changed
  • No new required request fields have been added
  • Default sorting, default values, error format, or existing error.code have not been changed
  • The impact of new enum values on old clients has been evaluated
  • A migration strategy has been clarified for breaking changes

Security Checklist

  • Unauthenticated returns 401, unauthorized returns 403 or is securely hidden as 404
  • Multi-tenant resources check tenant ownership
  • Do not expose passwordHash / token / secret / internal fields
  • sort/filter does not directly pass through database fields
  • Error messages do not leak internal implementation details