API 文档的痛点
写 API 文档是大多数开发者最不喜欢的工作之一。代码改了文档忘了更新,接口参数写得不清不楚,示例代码跑不通——这些问题几乎每个团队都遇到过。
AI 可以大幅减轻这个负担。我们来看一套完整的 API 文档生成提示词。
提示词 1:从代码生成 OpenAPI Spec
你是一个 API 文档专家。请根据以下代码生成 OpenAPI 3.0 规范的 YAML 文档。
代码:
```[语言]
[你的 API 代码]
要求:
- 完整的 OpenAPI 3.0 格式
- 每个端点包含:描述、参数、请求体、响应、错误码
- 使用 components/schemas 定义可复用的数据模型
- 包含认证方式说明
- 包含示例值(example)
### 使用示例
输入代码:
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
email: str
name: str
password: str
class UserResponse(BaseModel):
id: int
email: str
name: str
@app.post("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate):
"""创建新用户"""
pass
@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
"""获取用户信息"""
pass
@app.get("/users", response_model=list[UserResponse])
async def list_users(page: int = 1, size: int = 20):
"""获取用户列表"""
pass
AI 生成的 OpenAPI Spec:
openapi: 3.0.3
info:
title: User Management API
description: 用户管理接口
version: 1.0.0
paths:
/users:
post:
summary: 创建新用户
operationId: createUser
tags:
- Users
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserCreate'
example:
email: "user@example.com"
name: "张三"
password: "secure_password_123"
responses:
'201':
description: 用户创建成功
content:
application/json:
schema:
$ref: '#/components/schemas/UserResponse'
example:
id: 1
email: "user@example.com"
name: "张三"
'400':
description: 请求参数错误
'409':
description: 邮箱已存在
get:
summary: 获取用户列表
operationId: listUsers
tags:
- Users
parameters:
- name: page
in: query
schema:
type: integer
default: 1
minimum: 1
description: 页码
- name: size
in: query
schema:
type: integer
default: 20
minimum: 1
maximum: 100
description: 每页数量
responses:
'200':
description: 成功返回用户列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/UserResponse'
/users/{user_id}:
get:
summary: 获取用户信息
operationId: getUser
tags:
- Users
parameters:
- name: user_id
in: path
required: true
schema:
type: integer
description: 用户 ID
responses:
'200':
description: 成功返回用户信息
content:
application/json:
schema:
$ref: '#/components/schemas/UserResponse'
'404':
description: 用户不存在
components:
schemas:
UserCreate:
type: object
required:
- email
- name
- password
properties:
email:
type: string
format: email
description: 用户邮箱
name:
type: string
minLength: 1
maxLength: 100
description: 用户姓名
password:
type: string
minLength: 8
description: 密码(至少 8 位)
UserResponse:
type: object
properties:
id:
type: integer
description: 用户 ID
email:
type: string
description: 用户邮箱
name:
type: string
description: 用户姓名
提示词 2:生成接口使用文档
你是一个技术文档撰写专家。请根据以下 API 信息,生成面向开发者的接口使用文档。
API 信息:
[OpenAPI Spec 或接口描述]
文档要求:
1. 使用中文撰写,技术术语保留英文
2. 每个接口包含:
- 接口说明
- 请求方式和 URL
- 请求参数表格
- 请求示例(cURL + [语言])
- 成功响应示例
- 错误响应示例
3. 包含认证说明
4. 包含频率限制说明(如果有)
5. 包含常见问题
输出示例
## 创建用户
创建一个新的用户账号。
**请求**
POST /api/v1/users
**请求头**
| 名称 | 类型 | 必填 | 说明 |
|------|------|------|------|
| Authorization | string | 是 | Bearer token |
| Content-Type | string | 是 | application/json |
**请求参数**
| 名称 | 类型 | 必填 | 说明 |
|------|------|------|------|
| email | string | 是 | 用户邮箱,需要唯一 |
| name | string | 是 | 用户姓名,1-100 字符 |
| password | string | 是 | 密码,至少 8 位 |
**请求示例**
cURL:
```bash
curl -X POST https://api.example.com/api/v1/users \
-H "Authorization: Bearer your_token_here" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"name": "张三",
"password": "secure_password_123"
}'
Python:
import requests
response = requests.post(
"https://api.example.com/api/v1/users",
headers={"Authorization": "Bearer your_token_here"},
json={
"email": "user@example.com",
"name": "张三",
"password": "secure_password_123"
}
)
print(response.json())
成功响应(201)
{
"id": 1,
"email": "user@example.com",
"name": "张三"
}
错误响应
| 状态码 | 说明 |
|---|---|
| 400 | 请求参数错误 |
| 409 | 邮箱已存在 |
| 401 | 未认证 |
---
## 提示词 3:错误码文档生成
请为以下 API 设计并生成完整的错误码文档。
API 描述: [API 功能描述]
要求:
- 错误码格式:[前缀][模块码][错误序号],如 ERR_USER_001
- 每个错误码包含:
- 错误码
- HTTP 状态码
- 错误描述
- 可能的原因
- 解决方案
- 按模块分组
- 包含通用错误码(认证、权限、限流等)
### 输出示例
通用错误码
| 错误码 | HTTP 状态码 | 描述 | 原因 | 解决方案 |
|---|---|---|---|---|
| ERR_AUTH_001 | 401 | 未认证 | 缺少 Authorization header | 在请求头中添加有效的 Bearer token |
| ERR_AUTH_002 | 401 | Token 过期 | Token 已超过有效期 | 使用 refresh token 获取新的 access token |
| ERR_AUTH_003 | 403 | 权限不足 | 当前用户没有执行此操作的权限 | 联系管理员获取相应权限 |
| ERR_RATE_001 | 429 | 请求频率超限 | 超过 API 调用频率限制 | 降低请求频率,或升级 API 套餐 |
| ERR_SYS_001 | 500 | 服务器内部错误 | 服务端异常 | 稍后重试,如持续出现请联系技术支持 |
用户模块错误码
| 错误码 | HTTP 状态码 | 描述 | 原因 | 解决方案 |
|---|---|---|---|---|
| ERR_USER_001 | 400 | 邮箱格式错误 | 提供的邮箱不符合格式要求 | 检查邮箱格式 |
| ERR_USER_002 | 409 | 邮箱已注册 | 该邮箱已被其他用户使用 | 使用其他邮箱或找回密码 |
| ERR_USER_003 | 404 | 用户不存在 | 指定的用户 ID 不存在 | 检查用户 ID 是否正确 |
| ERR_USER_004 | 400 | 密码强度不足 | 密码不满足复杂度要求 | 密码需至少 8 位,包含字母和数字 |
---
## 提示词 4:SDK 使用示例生成
请根据以下 API 文档,生成 [语言] SDK 的使用示例。
API 文档: [API 描述或 OpenAPI Spec]
要求:
- 覆盖所有主要接口
- 包含初始化/认证
- 包含错误处理
- 包含分页处理
- 代码可以直接运行
- 添加注释说明
### 输出示例
```typescript
// TypeScript SDK 使用示例
import { ApiClient, UserApi } from '@example/sdk';
// 初始化客户端
const client = new ApiClient({
baseUrl: 'https://api.example.com/v1',
apiKey: 'your_api_key_here',
});
const userApi = new UserApi(client);
// 创建用户
async function createUser() {
try {
const user = await userApi.create({
email: 'user@example.com',
name: '张三',
password: 'secure_password_123',
});
console.log('创建成功:', user.id);
return user;
} catch (error) {
if (error.code === 'ERR_USER_002') {
console.error('邮箱已存在');
} else {
console.error('创建失败:', error.message);
}
throw error;
}
}
// 获取用户
async function getUser(userId: number) {
try {
const user = await userApi.get(userId);
console.log('用户信息:', user);
return user;
} catch (error) {
if (error.status === 404) {
console.error('用户不存在');
}
throw error;
}
}
// 分页获取用户列表
async function listAllUsers() {
const allUsers = [];
let page = 1;
const pageSize = 20;
while (true) {
const users = await userApi.list({ page, size: pageSize });
allUsers.push(...users);
// 如果返回数量少于 pageSize,说明已经是最后一页
if (users.length < pageSize) {
break;
}
page++;
}
console.log(`共获取 ${allUsers.length} 个用户`);
return allUsers;
}
// 运行示例
async function main() {
const newUser = await createUser();
await getUser(newUser.id);
await listAllUsers();
}
main().catch(console.error);
提示词 5:Changelog 生成
请根据以下 API 变更信息,生成 API Changelog。
变更信息:
[描述 API 的变更]
格式要求:
1. 按版本号和日期组织
2. 变更类型标记:新增、修改、废弃、移除
3. 包含迁移指南(如果有破坏性变更)
4. 包含影响范围说明
输出示例
## API Changelog
### v2.1.0 (2026-03-11)
#### 新增
- `GET /users/search` - 支持按姓名和邮箱搜索用户
- `PATCH /users/{id}` - 支持部分更新用户信息
- 所有列表接口支持 `sort` 参数
#### 修改
- `POST /users` - 密码最小长度从 6 位改为 8 位
- `GET /users` - 默认分页大小从 50 改为 20
#### 废弃
- `GET /users/all` - 请使用 `GET /users?size=1000` 替代,将在 v3.0 移除
### 迁移指南
**密码长度变更**
如果你的注册表单允许 6-7 位密码,需要更新前端验证规则:
```javascript
// 旧规则
const MIN_PASSWORD_LENGTH = 6;
// 新规则
const MIN_PASSWORD_LENGTH = 8;
分页大小变更 如果你依赖默认的 50 条分页,需要显式传入 size 参数:
// 旧方式(默认返回 50 条)
GET /users
// 新方式(显式指定 50 条)
GET /users?size=50
---
## 提示词 6:API 对比文档
请对比以下两个版本的 API,生成差异文档。
旧版本 API: [旧版 OpenAPI Spec 或描述]
新版本 API: [新版 OpenAPI Spec 或描述]
请输出:
- 新增的接口
- 删除的接口
- 修改的接口(参数变化、响应变化)
- 破坏性变更列表
- 迁移建议
---
## 提示词 7:从文档生成 Mock 数据
请根据以下 API 文档,生成 Mock 数据和 Mock Server 配置。
API 文档: [API 描述]
要求:
- 每个接口生成 3-5 条 Mock 数据
- Mock 数据要真实合理(不要用 “test123” 这种)
- 覆盖正常响应和错误响应
- 输出 [MSW/json-server/Mockoon] 格式的配置
### MSW 格式输出示例
```typescript
// mocks/handlers.ts
import { http, HttpResponse } from 'msw';
const users = [
{ id: 1, email: 'zhang.san@company.com', name: '张三' },
{ id: 2, email: 'li.si@company.com', name: '李四' },
{ id: 3, email: 'wang.wu@company.com', name: '王五' },
];
let nextId = 4;
export const handlers = [
// 获取用户列表
http.get('/api/v1/users', ({ request }) => {
const url = new URL(request.url);
const page = parseInt(url.searchParams.get('page') || '1');
const size = parseInt(url.searchParams.get('size') || '20');
const start = (page - 1) * size;
const end = start + size;
const paginatedUsers = users.slice(start, end);
return HttpResponse.json(paginatedUsers);
}),
// 创建用户
http.post('/api/v1/users', async ({ request }) => {
const body = await request.json();
// 模拟邮箱重复
if (users.some(u => u.email === body.email)) {
return HttpResponse.json(
{ code: 'ERR_USER_002', message: '邮箱已注册' },
{ status: 409 }
);
}
const newUser = { id: nextId++, email: body.email, name: body.name };
users.push(newUser);
return HttpResponse.json(newUser, { status: 201 });
}),
// 获取单个用户
http.get('/api/v1/users/:id', ({ params }) => {
const user = users.find(u => u.id === parseInt(params.id));
if (!user) {
return HttpResponse.json(
{ code: 'ERR_USER_003', message: '用户不存在' },
{ status: 404 }
);
}
return HttpResponse.json(user);
}),
];
工作流:完整的 API 文档生成流程
代码 → [提示词 1] → OpenAPI Spec
↓
[提示词 2] → 接口使用文档
↓
[提示词 3] → 错误码文档
↓
[提示词 4] → SDK 示例
↓
[提示词 7] → Mock 数据
每次 API 变更后:
旧 Spec + 新代码 → [提示词 1] → 新 Spec
↓
旧 Spec + 新 Spec → [提示词 6] → 差异文档
↓
[提示词 5] → Changelog
实用技巧
1. 保持 Spec 和代码同步
最好的做法是把 OpenAPI Spec 作为 Single Source of Truth,从 Spec 生成代码(而不是反过来)。但如果你的项目已经是代码优先,那就用 AI 定期从代码同步 Spec。
2. 文档也要做 Code Review
AI 生成的文档可能有错误。把文档纳入 PR 审查流程。
3. 用真实数据验证示例
AI 生成的 cURL 示例和 SDK 示例,一定要实际运行一遍确认能跑通。
4. 多语言示例
如果你的 API 面向多种语言的开发者,用提示词 4 分别生成 Python、JavaScript、Go、Java 的示例。
API 文档是你的产品和开发者之间的桥梁。好的文档让开发者 5 分钟就能上手,差的文档让他们 5 小时还在骂街。用 AI 把文档做好,是对开发者最大的尊重。
相关文章
评论
加载中...
评论
加载中...