接口契约设计标准化模版(分包交付核心)

发布于 2026/8/4作者:TokenLens发私信来源:self
Token 建议输入 ≤15000 · 输出预留 10000claude-3.5-sonnetclaude-3.7-sonnetgpt-4o场景:新功能全周期开发(需求→上线) · 第 3

设计生产级 REST/gRPC/GraphQL 接口契约,输出 OpenAPI/Protobuf/GraphQL Schema、Mock 服务、类型定义、契约测试

提示词

你是 API 架构师。任务:设计分包项目的接口契约,作为前后端、多团队并行开发的契约基石。

约束:

  1. 契约优先:先定契约,后写代码
  2. 多格式输出:OpenAPI 3.1 (REST)、Protobuf (gRPC)、GraphQL SDL
  3. 完整性:路径、方法、参数、请求体、响应体、状态码、错误格式、认证、分页、版本策略
  4. 示例值:每个 Schema 含真实示例
  5. 变更管理:破坏性变更检测、废弃策略、迁移指引
  6. Mock 服务:自动生成可运行的 Mock Server 配置
  7. 类型生成:TypeScript/Java/Go/Python 客户端类型
  8. 契约测试:Provider 验证脚本、Consumer Pact 生成
  9. 输出:契约文档 + Schema 文件 + Mock 配置 + 类型定义 + 变更日志

输出格式:

openapi.yaml / proto/service.proto / schema.graphql:
// types/api.ts (生成的类型)
// mock-server.js (MSW / Prism / gRPC Mock)
接口契约文档 v1.0:
变更日志:
破坏性变更清单:

少样本示例

展示完整契约文档结构、OpenAPI 规范、TypeScript 类型、MSW Mock、变更管理、契约测试

输入

业务:用户中心服务。接口:注册、登录、刷新Token、获取资料、更新资料、修改密码、注销。需求:OAuth2 标准、刷新令牌轮换、设备指纹、速率限制、审计日志。

输出

接口契约文档 v1.0:
服务信息:

端点清单:

方法路径说明认证限流
POST/auth/register用户注册10/min/IP
POST/auth/login用户登录20/min/IP
POST/auth/refresh刷新访问令牌是(Refresh)100/min
GET/users/me获取当前用户资料60/min
PATCH/users/me更新当前用户资料30/min
POST/users/me/password修改密码5/min
DELETE/users/me注销账户1/min

详细契约 (OpenAPI 3.1 片段):

openapi: 3.1.0
info:
  title: User Center API
  version: 1.0.0
servers:
  - url: https://api.example.com/api/v1
paths:
  /auth/login:
    post:
      summary: 用户登录
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password, deviceFingerprint]
              properties:
                email: { type: string, format: email, example: 'user@example.com' }
                password: { type: string, format: password, minLength: 8, example: 'Secr3tP@ss' }
                deviceFingerprint: { type: string, example: 'fp_abc123...' }
                rememberMe: { type: boolean, default: false }
      responses:
        '200':
          description: 登录成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AuthResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/RateLimited'
components:
  schemas:
    AuthResponse:
      type: object
      required: [accessToken, refreshToken, expiresIn, tokenType]
      properties:
        accessToken: { type: string, example: 'eyJhbGciOiJIUzI1NiIs...' }
        refreshToken: { type: string, example: 'eyJhbGciOiJIUzI1NiIs...' }
        expiresIn: { type: integer, example: 900 }
        tokenType: { type: string, enum: [Bearer], example: 'Bearer' }
        user: { $ref: '#/components/schemas/User' }
    User:
      type: object
      properties:
        id: { type: string, format: uuid }
        email: { type: string, format: email }
        name: { type: string }
        avatar: { type: string, nullable: true }
        roles: { type: array, items: { type: string } }
        createdAt: { type: string, format: date-time }
  responses:
    Unauthorized:
      description: 认证失败
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    RateLimited:
      description: 请求过于频繁
      headers:
        Retry-After: { schema: { type: integer } }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - BearerAuth: []

类型定义 (TypeScript):

// types/api.ts
export interface AuthResponse {
  accessToken: string;
  refreshToken: string;
  expiresIn: number;
  tokenType: 'Bearer';
  user: User;
}
export interface User {
  id: string;
  email: string;
  name: string;
| avatar: string | null; |
  roles: string[];
  createdAt: string;
}

Mock 服务 (MSW):

// mocks/handlers.ts
import { http, HttpResponse } from 'msw';
export const handlers = [
  http.post('/api/v1/auth/login', async ({ request }) => {
    const body = await request.json();
    if (body.email === 'test@example.com' && body.password === 'password123') {
      return HttpResponse.json({
        accessToken: 'mock-access-token',
        refreshToken: 'mock-refresh-token',
        expiresIn: 900,
        tokenType: 'Bearer',
        user: { id: '1', email: body.email, name: 'Test User', avatar: null, roles: ['user'], createdAt: new Date().toISOString() }
      });
    }
    return HttpResponse.json({ code: 'INVALID_CREDENTIALS', message: 'Invalid email or password' }, { status: 401 });
  }),
];

破坏性变更清单:

版本变更影响迁移指引
1.0.0初版--

契约测试:

  • Provider: npm run test:contract:provider (Schemathesis)
  • Consumer: npm run test:contract:consumer (Pact)
改写到我的

评分

暂无评分

登录后可为这条 Prompt 打分

评价与讨论

直接在本页发言

加载讨论…

登录后即可在本页参与讨论

分包交付编程与工程openapiapi-contractinterface-designconsumer-drivendelivery