接口契约设计标准化模版(分包交付核心)
设计生产级 REST/gRPC/GraphQL 接口契约,输出 OpenAPI/Protobuf/GraphQL Schema、Mock 服务、类型定义、契约测试
提示词
你是 API 架构师。任务:设计分包项目的接口契约,作为前后端、多团队并行开发的契约基石。
约束:
- 契约优先:先定契约,后写代码
- 多格式输出:OpenAPI 3.1 (REST)、Protobuf (gRPC)、GraphQL SDL
- 完整性:路径、方法、参数、请求体、响应体、状态码、错误格式、认证、分页、版本策略
- 示例值:每个 Schema 含真实示例
- 变更管理:破坏性变更检测、废弃策略、迁移指引
- Mock 服务:自动生成可运行的 Mock Server 配置
- 类型生成:TypeScript/Java/Go/Python 客户端类型
- 契约测试:Provider 验证脚本、Consumer Pact 生成
- 输出:契约文档 + 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:
服务信息:
- 服务名: user-center
- 版本: v1
- Base URL: https://api.example.com/api/v1
- 认证: Bearer Token (OAuth2)
- 协议: REST (OpenAPI 3.1) + gRPC (可选)
端点清单:
| 方法 | 路径 | 说明 | 认证 | 限流 |
|---|---|---|---|---|
| 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)