name: api-documentation description: 自动生成全面的API文档,包括示例、模式和交互式工具。
API 文档技能
自动生成全面的API文档,包括示例、模式和交互式工具。
指令
您是一个API文档专家。当被调用时:
-
生成文档:
- 创建API参考文档
- 从代码注释中提取信息
- 从OpenAPI/Swagger规范生成
- 包括使用示例
- 文档化认证方法
-
交互式文档:
- 设置Swagger UI
- 配置Redoc
- 创建交互式游乐场
- 添加试玩功能
- 包括代码样本
-
文档类型:
- API参考指南
- 入门教程
- 认证指南
- 错误处理文档
- 速率限制策略
-
多格式导出:
- HTML文档
- Markdown文件
- PDF导出
- Postman集合
- SDK生成
使用示例
@api-documentation
@api-documentation --from-openapi
@api-documentation --interactive
@api-documentation --export-postman
@api-documentation --generate-sdk
文档工具
Swagger UI
使用Express设置
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
// 加载OpenAPI规范
const swaggerDocument = YAML.load('./openapi.yaml');
// 提供Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: '我的API文档',
customfavIcon: '/favicon.ico'
}));
// 以JSON格式提供OpenAPI规范
app.get('/openapi.json', (req, res) => {
res.json(swaggerDocument);
});
app.listen(3000, () => {
console.log('API文档可在 http://localhost:3000/api-docs 访问');
});
自定义Swagger选项
const options = {
explorer: true,
swaggerOptions: {
persistAuthorization: true,
displayRequestDuration: true,
filter: true,
syntaxHighlight: {
activate: true,
theme: 'monokai'
}
},
customCss: `
.swagger-ui .topbar { background-color: #2c3e50; }
.swagger-ui .info .title { color: #2c3e50; }
`,
customSiteTitle: '我的API - 文档',
customfavIcon: '/assets/favicon.ico'
};
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
Redoc
设置
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
// 提供OpenAPI规范
app.get('/openapi.yaml', (req, res) => {
res.sendFile(__dirname + '/openapi.yaml');
});
// 提供Redoc
app.get('/docs', (req, res) => {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>API 文档</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
<style>
body { margin: 0; padding: 0; }
</style>
</head>
<body>
<redoc spec-url='/openapi.yaml'></redoc>
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
</body>
</html>
`);
});
app.listen(3000);
Redoc CLI
# 安装
npm install -g redoc-cli
# 生成静态HTML
redoc-cli bundle openapi.yaml -o docs/index.html
# 使用实时重载提供服务
redoc-cli serve openapi.yaml --watch
# 自定义选项
redoc-cli bundle openapi.yaml \
--output docs/index.html \
--title "我的API文档" \
--options.theme.colors.primary.main="#2c3e50"
Stoplight Elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>API 文档</title>
<script src="https://unpkg.com/@stoplight/elements/web-components.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@stoplight/elements/styles.min.css" />
</head>
<body>
<elements-api
apiDescriptionUrl="/openapi.yaml"
router="hash"
layout="sidebar"
/>
</body>
</html>
从代码生成文档
JSDoc 到 OpenAPI
/**
* @openapi
* /api/users:
* get:
* summary: 获取所有用户
* description: 检索所有用户的分页列表
* tags:
* - 用户
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* minimum: 1
* default: 1
* description: 页码
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* maximum: 100
* default: 10
* description: 每页项目数
* responses:
* 200:
* description: 成功响应
* content:
* application/json:
* schema:
* type: object
* properties:
* data:
* type: array
* items:
* $ref: '#/components/schemas/User'
* meta:
* $ref: '#/components/schemas/PaginationMeta'
* 401:
* $ref: '#/components/responses/UnauthorizedError'
* security:
* - bearerAuth: []
*/
router.get('/users', async (req, res) => {
// 实现
});
/**
* @openapi
* components:
* schemas:
* User:
* type: object
* required:
* - id
* - name
* - email
* properties:
* id:
* type: string
* description: 用户ID
* example: "123"
* name:
* type: string
* description: 用户全名
* example: "John Doe"
* email:
* type: string
* format: email
* description: 用户电子邮件地址
* example: "john@example.com"
*/
TypeDoc (TypeScript)
/**
* 用户管理API
* @module UserAPI
*/
/**
* 代表系统中的用户
* @interface User
*/
interface User {
/** 唯一用户标识符 */
id: string;
/** 用户全名 */
name: string;
/** 用户电子邮件地址 */
email: string;
/** 用户角色 */
role: 'user' | 'admin';
}
/**
* 获取所有用户
* @route GET /api/users
* @param {number} page - 页码(默认: 1)
* @param {number} limit - 每页项目数(默认: 10)
* @returns {Promise<User[]>} 用户列表
* @throws {UnauthorizedError} 如果未认证
*/
export async function getUsers(
page: number = 1,
limit: number = 10
): Promise<User[]> {
// 实现
}
/**
* 创建新用户
* @route POST /api/users
* @param {CreateUserRequest} data - 用户数据
* @returns {Promise<User>} 创建的用户
* @throws {ValidationError} 如果数据无效
* @throws {ConflictError} 如果电子邮件已存在
*/
export async function createUser(data: CreateUserRequest): Promise<User> {
// 实现
}
Python Docstrings (FastAPI)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI(
title="用户管理API",
description="用于管理用户和认证的API",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
class User(BaseModel):
"""
用户模型,代表用户账户。
属性:
id: 唯一用户标识符
name: 用户全名
email: 用户电子邮件地址
role: 用户角色(用户或管理员)
"""
id: str
name: str
email: str
role: str = "user"
@app.get("/api/users", response_model=List[User], tags=["用户"])
async def get_users(
page: int = 1,
limit: int = 10
) -> List[User]:
"""
使用分页获取所有用户。
参数:
page: 页码(默认: 1)
limit: 每页项目数(默认: 10)
返回:
用户列表
抛出:
HTTPException: 如果未授权 (401)
"""
# 实现
return []
@app.post("/api/users", response_model=User, status_code=201, tags=["用户"])
async def create_user(user: User) -> User:
"""
创建新用户账户。
参数:
user: 用户数据,包括姓名、电子邮件和可选角色
返回:
创建的用户对象
抛出:
HTTPException: 如果验证失败 (400)
HTTPException: 如果电子邮件已存在 (409)
"""
# 实现
return user
文档模板
Markdown API 参考
# API 参考
基础URL: `https://api.example.com/v1`
## 认证
所有API请求需要使用Bearer令牌进行认证:
```bash
Authorization: Bearer YOUR_ACCESS_TOKEN
通过调用 /auth/login 端点获取您的访问令牌。
端点
用户
获取所有用户
GET /api/users
检索用户的分页列表。
参数
| 名称 | 类型 | 位置 | 必需 | 描述 |
|---|---|---|---|---|
| page | integer | 查询 | 否 | 页码(默认: 1) |
| limit | integer | 查询 | 否 | 每页项目数(最大: 100) |
响应
{
"data": [
{
"id": "123",
"name": "John Doe",
"email": "john@example.com",
"role": "user"
}
],
"meta": {
"page": 1,
"limit": 10,
"total": 42,
"totalPages": 5
}
}
状态码
200 OK- 成功401 Unauthorized- 缺少或无效的认证500 Internal Server Error- 服务器错误
示例请求
curl -X GET "https://api.example.com/v1/api/users?page=1&limit=10" \
-H "Authorization: Bearer YOUR_TOKEN"
const response = await fetch('https://api.example.com/v1/api/users?page=1&limit=10', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN'
}
});
const data = await response.json();
import requests
response = requests.get(
'https://api.example.com/v1/api/users',
headers={'Authorization': 'Bearer YOUR_TOKEN'},
params={'page': 1, 'limit': 10}
)
data = response.json()
创建用户
POST /api/users
创建新用户账户。
请求体
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePass123!",
"role": "user"
}
响应
{
"id": "123",
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"createdAt": "2024-01-15T10:30:00Z"
}
状态码
201 Created- 用户创建成功400 Bad Request- 无效的请求数据409 Conflict- 电子邮件已存在401 Unauthorized- 需要认证
错误处理
所有错误遵循一致格式:
{
"code": "ERROR_CODE",
"message": "人类可读的错误消息",
"details": {
"field": "额外的错误细节"
}
}
常见错误码
| 码 | HTTP 状态 | 描述 |
|---|---|---|
| UNAUTHORIZED | 401 | 需要认证 |
| FORBIDDEN | 403 | 权限不足 |
| NOT_FOUND | 404 | 资源未找到 |
| VALIDATION_ERROR | 400 | 无效的输入数据 |
| RATE_LIMIT_EXCEEDED | 429 | 请求过多 |
速率限制
API请求限制为:
- 每分钟100次请求 对于认证用户
- 每分钟20次请求 对于未认证请求
速率限制头包含在所有响应中:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1610000000
分页
所有列表端点支持分页,参数如下:
page- 页码(默认: 1)limit- 每页项目数(默认: 10,最大: 100)
响应包括分页元数据:
{
"data": [...],
"meta": {
"page": 1,
"limit": 10,
"total": 100,
"totalPages": 10
}
}
版本控制
API使用URL版本控制:
- 当前版本:
v1 - 基础URL:
https://api.example.com/v1
破坏性更改将在新版本中引入(v2, v3 等)
### 入门指南
```markdown
# 入门
本指南将帮助您进行首次API请求。
## 1. 获取您的API密钥
在 [https://example.com/signup](https://example.com/signup) 注册以获取API密钥。
## 2. 进行首次请求
### 使用curl
```bash
curl -X GET https://api.example.com/v1/api/users \
-H "Authorization: Bearer YOUR_API_KEY"
使用JavaScript
const response = await fetch('https://api.example.com/v1/api/users', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const users = await response.json();
console.log(users);
使用Python
import requests
response = requests.get(
'https://api.example.com/v1/api/users',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
users = response.json()
print(users)
3. 创建资源
curl -X POST https://api.example.com/v1/api/users \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com"
}'
4. 处理错误
始终检查响应状态:
try {
const response = await fetch('https://api.example.com/v1/api/users', {
headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
});
if (!response.ok) {
const error = await response.json();
console.error('错误:', error.message);
return;
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('网络错误:', error);
}
下一步
## 文档生成工具
### Docusaurus (Facebook)
```bash
# 创建新站点
npx create-docusaurus@latest my-docs classic
# 安装OpenAPI插件
npm install docusaurus-plugin-openapi-docs
# 配置
# docusaurus.config.js
module.exports = {
plugins: [
[
'docusaurus-plugin-openapi-docs',
{
id: 'api',
docsPluginId: 'classic',
config: {
api: {
specPath: 'openapi.yaml',
outputDir: 'docs/api',
sidebarOptions: {
groupPathsBy: 'tag'
}
}
}
}
]
]
};
# 生成文档
npm run docusaurus gen-api-docs all
# 提供
npm run start
Slate (Beautiful API Docs)
# 克隆模板
git clone https://github.com/slatedocs/slate.git my-api-docs
cd my-api-docs
# 安装依赖
bundle install
# 编辑 source/index.html.md
# 运行服务器
bundle exec middleman server
# 构建静态站点
bundle exec middleman build
ReadMe.io
# 安装CLI
npm install -g rdme
# 上传OpenAPI规范
rdme openapi openapi.yaml --key YOUR_README_API_KEY
# 与GitHub同步
rdme openapi openapi.yaml --github --key YOUR_README_API_KEY
MkDocs (Python)
# 安装
pip install mkdocs mkdocs-material
# 创建新项目
mkdocs new my-api-docs
cd my-api-docs
# 配置 mkdocs.yml
site_name: 我的API文档
theme:
name: material
features:
- navigation.tabs
- navigation.sections
- toc.integrate
nav:
- 主页: index.md
- 入门: getting-started.md
- API参考: api-reference.md
- 示例: examples.md
# 本地提供
mkdocs serve
# 构建
mkdocs build
代码示例生成器
自动代码生成
// 从OpenAPI规范
const CodeGen = require('openapi-client-axios-typegen');
async function generateSDK() {
const api = await CodeGen.generateClient('openapi.yaml');
// 生成的TypeScript客户端
const users = await api.getUsers({ page: 1, limit: 10 });
const newUser = await api.createUser({
name: 'John Doe',
email: 'john@example.com'
});
}
多语言示例
// 示例生成器.js
const examples = {
getUsersCurl: `curl -X GET "https://api.example.com/v1/api/users?page=1&limit=10" \\
-H "Authorization: Bearer YOUR_TOKEN"`,
getUsersJavaScript: `const response = await fetch('https://api.example.com/v1/api/users?page=1&limit=10', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN'
}
});
const data = await response.json();`,
getUsersPython: `import requests
response = requests.get(
'https://api.example.com/v1/api/users',
headers={'Authorization': 'Bearer YOUR_TOKEN'},
params={'page': 1, 'limit': 10}
)
data = response.json()`,
getUsersGo: `client := &http.Client{}
req, _ := http.NewRequest("GET", "https://api.example.com/v1/api/users?page=1&limit=10", nil)
req.Header.Add("Authorization", "Bearer YOUR_TOKEN")
resp, _ := client.Do(req)`,
getUsersRuby: `require 'net/http'
uri = URI('https://api.example.com/v1/api/users?page=1&limit=10')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer YOUR_TOKEN'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }`
};
最佳实践
文档内容
- 编写清晰、简洁的描述
- 包括多语言代码示例
- 提供真实世界用例
- 文档化所有错误码
- 包括速率限制和配额
- 显示认证示例
- 解释分页
- 文档化版本控制策略
交互功能
- 添加“试玩”功能
- 包括请求/响应示例
- 显示语法高亮
- 提供复制到剪贴板按钮
- 添加搜索功能
- 包括导航菜单
维护
- 保持文档与代码同步
- 自动化文档生成
- 版本控制文档与API
- 定期审查和更新
- 测试所有代码示例
- 收集用户反馈
SEO和发现
- 使用描述性标题
- 添加元描述
- 创建站点地图
- 使用适当的标题结构
- 包括关键词
- 使文档公开可访问
注释
- 尽可能从OpenAPI规范自动生成文档
- 包括交互式API浏览器
- 提供多种编程语言的示例
- 保持文档与代码更改同步
- 使用版本控制管理文档
- 使文档可搜索
- 包括入门指南
- 彻底文档化认证
- 显示错误处理示例
- 发布前测试所有代码示例
- 收集并融入用户反馈
- 使用一致的格式和风格