REST API 设计 + OpenAPI 3.1 规范生成
Token 建议输入 ≤15000 · 输出预留 10000gpt-4oclaude-3.5-sonnet
从业务需求生成 RESTful API 设计,输出 OpenAPI 3.1 规范文档、TypeScript 类型、Mock 服务器配置
提示词
你是 API 架构师。任务:基于业务描述设计 REST API,产出 OpenAPI 3.1 规范。
约束:
- 遵循 REST 成熟度模型 Level 3(HATEOAS 可选)
- 命名:kebab-case 路径,复数资源名,标准 HTTP 方法
- 状态码:200/201/204/400/401/403/404/409/422/500 语义准确
- 请求/响应体:JSON Schema 定义,含示例值
- 分页:cursor-based(首选)或 offset/limit,统一 envelope
- 错误格式:RFC 7807 Problem Details(type, title, status, detail, instance)
- 认证:Bearer Token(OAuth2/JWT),OpenAPI securitySchemes 定义
- 版本策略:URL 前缀 /api/v1/,废弃策略说明
- 输出:openapi.yaml + types/api.ts + mock-server.config.js
输出格式:
openapi.yaml:
// types/api.ts
// mock-server.config.js
少样本示例
展示完整 OpenAPI 结构、枚举、分页、错误规范、安全定义
输入
业务:电商订单系统。需求:创建订单、查询订单列表(分页)、查询订单详情、取消订单、申请退款。订单状态:pending/paid/shipped/delivered/cancelled/refunded。
输出
openapi.yaml 片段:
openapi: 3.1.0
info:
title: Order API
version: 1.0.0
servers:
- url: https://api.example.com/api/v1
paths:
/orders:
post:
summary: Create order
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateOrderRequest'
responses:
'201':
description: Created
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
'422':
$ref: '#/components/responses/ValidationError'
get:
summary: List orders
parameters:
- $ref: '#/components/parameters/CursorPagination'
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/OrderListResponse'
/orders/{id}:
get:
summary: Get order
parameters:
- $ref: '#/components/schemas/OrderIdParam'
responses:
'200':
$ref: '#/components/schemas/Order'
'404':
$ref: '#/components/responses/NotFound'
patch:
summary: Cancel order
responses:
'200':
$ref: '#/components/schemas/Order'
'409':
$ref: '#/components/responses/Conflict'
components:
schemas:
CreateOrderRequest:
type: object
required: [items, shippingAddress]
properties:
items:
type: array
items: { $ref: '#/components/schemas/OrderItem' }
shippingAddress: { $ref: '#/components/schemas/Address' }
Order:
type: object
properties:
id: { type: string, format: uuid }
status: { type: string, enum: [pending, paid, shipped, delivered, cancelled, refunded] }
items: { type: array, items: { $ref: '#/components/schemas/OrderItem' } }
totalAmount: { type: integer, minimum: 0 }
createdAt: { type: string, format: date-time }
OrderListResponse:
type: object
properties:
data: { type: array, items: { $ref: '#/components/schemas/Order' } }
nextCursor: { type: string, nullable: true }
parameters:
CursorPagination:
name: cursor
in: query
schema: { type: string }
OrderIdParam:
name: id
in: path
required: true
schema: { type: string, format: uuid }
responses:
ValidationError:
description: Validation failed
content:
application/json:
schema: { $ref: '#/components/schemas/ProblemDetails' }
NotFound:
description: Not found
Conflict:
description: State conflict
securitySchemes:
BearerAuth:
type: http
scheme: bearer
security: - BearerAuth: []