关于 api-documentation-writer
api-documentation-writer 是帮助开发者编写和维护 API 文档的技能,涵盖 OpenAPI/Swagger 规范、端点参考、认证、错误、变更日志及多语言代码示例。
主要功能
- 01OpenAPI/Swagger 规范
- 02端点与认证参考
- 03错误代码及处理指引
- 04多语言代码示例
- 05变更日志与交互式文档
适用场景
- 01编写新 API 或端点文档
- 02撰写认证与错误指南
- 03添加多种语言的代码示例
- 04维护 API 变更日志
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ eddiebe147/ claude-settings --skill api-documentation-writer安装后在 Claude Code 中输入/api-documentation-writer确认已加载。
详细介绍
API 文档编写技能
概述
此技能可帮助你编写清晰、全面且深受开发者喜爱的 API 文档。涵盖 OpenAPI/Swagger 规范、端点参考、身份验证指南、多种语言的代码示例,以及开发者体验最佳实践。
文档理念
三个 C
- 清晰(Clear):解释明确、没有行话
- 完整(Complete):记录所有参数、响应和边缘情况
- 及时(Current):始终与实际 API 行为保持同步
应记录的内容
- 应做:记录每个公开端点
- 应做:为所有场景提供请求/响应示例
- 应做:记录错误代码及修正步骤
- 应做:提供常用语言的代码示例
- 不应做:记录内部/私有端点
- 不应做:假设读者了解你的领域
- 不应做:让文档与实现脱节
OpenAPI 规范
基本结构
# openapi.yaml
openapi: 3.1.0
info:
title: My API
version: 1.0.0
description: |
Welcome to the My API documentation.
## Getting Started
1. Sign up for an API key at [dashboard.example.com](https://dashboard.example.com)
2. Include your key in the `Authorization` header
3. Start making requests!
## Rate Limits
- Free tier: 100 requests/minute
- Pro tier: 1000 requests/minute
contact:
name: API Support
email: [email protected]
url: https://support.example.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
servers:
- url: https://api.example.com/v1
description: Production
- url: https://staging-api.example.com/v1
description: Staging
tags:
- name: Users
description: User management operations
- name: Items
description: Item CRUD operations
端点文档
paths:
/users:
get:
tags:
- Users
summary: List all users
description: |
Retrieves a paginated list of users. Results are sorted by creation date (newest first).
**Permissions required:** `users:read`
operationId: listUsers
parameters:
- name: page
in: query
description: Page number (1-indexed)
required: false
schema:
type: integer
minimum: 1
default: 1
example: 1
- name: limit
in: query
description: Number of results per page (max 100)
required: false
schema:
type: integer
minimum: 1
maximum: 100
default: 20
example: 20
- name: status
in: query
description: Filter by user status
required: false
schema:
type: string
enum: [active, inactive, pending]
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
example:
data:
- id: "usr_123"
email: "[email protected]"
name: "John Doe"
status: "active"
created_at: "2024-01-15T10:30:00Z"
meta:
page: 1
limit: 20
total: 150
total_pages: 8
'401':
$ref: '#/components/responses/Unauthorized'
'403':
$ref: '#/components/responses/Forbidden'
'429':
$ref: '#/components/responses/RateLimited'
post:
tags:
- Users
summary: Create a new user
description: |
Creates a new user account. An email verification will be sent to the provided address.
**Permissions required:** `users:write`
operationId: createUser
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
examples:
basic:
summary: Basic user creation
value:
email: "[email protected]"
name: "Jane Doe"
with_metadata:
summary: User with metadata
value:
email: "[email protected]"
name: "Jane Doe"
metadata:
department: "Engineering"
role: "Developer"
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
$ref: '#/components/responses/BadRequest'
'409':
description: User with this email already exists
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error:
code: "USER_EXISTS"
message: "A user with this email already exists"
Schema 定义
components:
schemas:
User:
type: object
description: Represents a user in the system
required:
- id
- email
- status
- created_at
properties:
id:
type: string
description: Unique identifier (prefixed with `usr_`)
pattern: '^usr_[a-zA-Z0-9]+$'
example: "usr_123abc"
email:
type: string
format: email
description: User's email address (unique)
example: "[email protected]"
name:
type: string
description: User's display name
maxLength: 100
example: "John Doe"
status:
type: string
enum: [active, inactive, pending]
description: |
Account status:
- `active`: User can sign in and use the service
- `inactive`: Account has been deactivated
- `pending`: Awaiting email verification
example: "active"
metadata:
type: object
additionalProperties: true
description: Custom key-value pairs for storing additional data
example:
department: "Engineering"
created_at:
type: string
format: date-time
description: ISO 8601 timestamp of account creation
example: "2024-01-15T10:30:00Z"
updated_at:
type: string
format: date-time
description: ISO 8601 timestamp of last update
example: "2024-01-16T14:45:00Z"
CreateUserRequest:
type: object
required:
- email
properties:
email:
type: string
format: email
description: Email address for the new user (must be unique)
name:
type: string
description: User's display name
maxLength: 100
metadata:
type: object
additionalProperties: true
Error:
type: object
required:
- error
properties:
error:
type: object
required:
- code
- message
properties:
code:
type: string
description: Machine-readable error code
message:
type: string
description: Human-readable error description
details:
type: array
description: Additional error details for validation errors
items:
type: object
properties:
field:
type: string
message:
type: string
身份验证文档
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: |
JWT token obtained from the `/auth/token` endpoint.
Include in requests as:
```
Authorization: Bearer <your-token>
```
Tokens expire after 1 hour. Use refresh tokens for long-lived sessions.
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
description: |
API key for server-to-server communication.
Obtain your key from the [Developer Dashboard](https://dashboard.example.com).
Include in requests as:
```
X-API-Key: <your-api-key>
```
security:
- BearerAuth: []
- ApiKeyAuth: []
可复用响应
components:
responses:
BadRequest:
description: Invalid request parameters
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
examples:
validation_error:
summary: Validation error
value:
error:
code: "VALIDATION_ERROR"
message: "Request validation failed"
details:
- field: "email"
message: "Must be a valid email address"
missing_field:
summary: Missing required field
value:
error:
code: "MISSING_FIELD"
message: "Required field 'email' is missing"
Unauthorized:
description: Missing or invalid authentication
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error:
code: "UNAUTHORIZED"
message: "Invalid or expired authentication token"
Forbidden:
description: Insufficient permissions
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error:
code: "FORBIDDEN"
message: "You don't have permission to access this resource"
NotFound:
description: Resource not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error:
code: "NOT_FOUND"
message: "The requested resource was not found"
RateLimited:
description: Rate limit exceeded
headers:
X-RateLimit-Limit:
schema:
type: integer
description: Request limit per minute
X-RateLimit-Remaining:
schema:
type: integer
description: Remaining requests in current window
X-RateLimit-Reset:
schema:
type: integer
description: Unix timestamp when the rate limit resets
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error:
code: "RATE_LIMITED"
message: "Too many requests. Please retry after 60 seconds"
Markdown 文档
端点参考模板
# Create User
Create a new user account.
## Endpoint
POST /v1/users
## Authentication
Requires API key with `users:write` permission.
## Request Body
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `email` | string | Yes | User's email address (must be unique) |
| `name` | string | No | Display name (max 100 characters) |
| `metadata` | object | No | Custom key-value pairs |
### Example Request
```bash
curl -X POST https://api.example.com/v1/users \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"name": "Jane Doe"
}'
响应
成功(201 Created)
{
"id": "usr_abc123",
"email": "[email protected]",
"name": "Jane Doe",
"status": "pending",
"created_at": "2024-01-15T10:30:00Z"
}
错误
| 状态码 | 代码 | 描述 |
|---|---|---|
| 400 | VALIDATION_ERROR | 电子邮件格式无效或缺少必填字段 |
| 401 | UNAUTHORIZED | 身份验证无效或缺失 |
| 409 | USER_EXISTS | 已存在使用此电子邮件的用户 |
| 429 | RATE_LIMITED | 请求过多 |
错误示例
{
"error": {
"code": "USER_EXISTS",
"message": "A user with this email already exists"
}
}
## Code Examples
### Multi-Language Examples
```markdown
## Code Examples
### cURL
```bash
curl -X GET "https://api.example.com/v1/users?limit=10" \
-H "Authorization: Bearer YOUR_TOKEN"
JavaScript(fetch)
const response = await fetch('https://api.example.com/v1/users?limit=10', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN'
}
});
const data = await response.json();
console.log(data);
JavaScript(axios)
import axios from 'axios';
const { data } = await axios.get('https://api.example.com/v1/users', {
params: { limit: 10 },
headers: {
'Authorization': 'Bearer YOUR_TOKEN'
}
});
Python
import requests
response = requests.get(
'https://api.example.com/v1/users',
params={'limit': 10},
headers={'Authorization': 'Bearer YOUR_TOKEN'}
)
data = response.json()
print(data)
Ruby
require 'net/http'
require 'json'
uri = URI('https://api.example.com/v1/users?limit=10')
request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer YOUR_TOKEN'
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
data = JSON.parse(response.body)
puts data
Go
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
req, _ := http.NewRequest("GET", "https://api.example.com/v1/users?limit=10", nil)
req.Header.Set("Authorization", "Bearer YOUR_TOKEN")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
var data map[string]interface{}
json.NewDecoder(resp.Body).Decode(&data)
fmt.Println(data)
}
## Error Documentation
### Error Code Reference
```markdown
# Error Codes
All API errors follow a consistent format:
```json
{
"error": {
"code": "ERROR_CODE",
"message": "Human-readable description",
"details": [] // Optional additional information
}
}
身份验证错误
| 代码 | HTTP 状态 | 描述 | 解决方法 |
|---|---|---|---|
UNAUTHORIZED | 401 | 缺少令牌或令牌无效 | 添加有效的 Authorization 请求头 |
TOKEN_EXPIRED | 401 | 令牌已过期 | 通过 /auth/token 获取新令牌 |
INVALID_API_KEY | 401 | 无法识别 API 密钥 | 在控制面板中检查你的 API 密钥 |
FORBIDDEN | 403 | 权限不足 | 为令牌申请适当的作用域 |
验证错误
| 代码 | HTTP 状态 | 描述 | 解决方法 |
|---|---|---|---|
VALIDATION_ERROR | 400 | 请求正文验证失败 | 查看 details 数组以了解具体字段 |
MISSING_FIELD | 400 | 未提供必填字段 | 添加所有必填字段 |
INVALID_FORMAT | 400 | 字段格式不正确 | 按预期格式填写(参见 schema) |
资源错误
| 代码 | HTTP 状态 | 描述 | 解决方法 |
|---|---|---|---|
NOT_FOUND | 404 | 资源不存在 | 确认资源 ID 正确 |
ALREADY_EXISTS | 409 | 资源已存在 | 使用其他标识符或更新现有资源 |
CONFLICT | 409 | 状态冲突 | 刷新后重试操作 |
速率限制
| 代码 | HTTP 状态 | 描述 | 解决方法 |
|---|---|---|---|
RATE_LIMITED | 429 | 请求过多 | 等待后重试(参见 Retry-After 请求头) |
## Changelog Documentation
### API Changelog Format
```markdown
# API Changelog
## 2024-01-15 - v1.2.0
### Added
- `GET /users/{id}/activity` - Retrieve user activity history
- `metadata` field on User object for custom data storage
### Changed
- Pagination now 1-indexed (previously 0-indexed)
- Rate limits increased: Free tier 100 → 200 req/min
### Deprecated
- `GET /users/search` - Use `GET /users` with query parameters instead
- Will be removed in v2.0.0
### Fixed
- `created_at` now correctly returns UTC timezone
---
## 2024-01-01 - v1.1.0
### Added
- Webhook support for user events
- `status` filter on `GET /users`
### Security
- API keys now support IP allowlisting
交互式文档
Swagger UI 配置
// swagger-config.js
const swaggerUiOptions = {
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: 'API Documentation',
customfavIcon: '/favicon.ico',
swaggerOptions: {
persistAuthorization: true,
displayRequestDuration: true,
filter: true,
tryItOutEnabled: true,
},
};
Redoc 配置
# redoc.yaml
x-tagGroups:
- name: Getting Started
tags:
- Authentication
- name: Core Resources
tags:
- Users
- Items
- name: Utilities
tags:
- Webhooks
- Health
x-logo:
url: 'https://example.com/logo.png'
altText: 'API Logo'
文档检查清单
每个端点
- 摘要(一行)
- 描述(详细说明)
- 记录所有参数及其类型和示例
- 提供所有响应代码的示例
- 记录错误代码及修正步骤
- 至少使用 2 种语言提供代码示例
- 说明身份验证要求
整体 API
- 入门指南
- 提供示例的身份验证指南
- 速率限制文档
- 分页模式
- 错误处理指南
- 持续维护变更日志
- 记录版本控制策略
- SDK/库链接
开发者体验
- 交互式“试用”功能
- 可直接复制粘贴的示例
- 术语一致
- 搜索功能
- 适配移动设备的渲染
工具集成
从代码生成
# From Express/Node.js routes
npx swagger-jsdoc -d swaggerDef.js -o openapi.yaml
# From TypeScript types
npx openapi-typescript-codegen --input openapi.yaml --output ./sdk
验证 OpenAPI
# Validate spec
npx @redocly/cli lint openapi.yaml
# Preview documentation
npx @redocly/cli preview-docs openapi.yaml
何时使用此技能
在以下情况下调用此技能:
- 从头开始创建新的 API 文档
- 为新端点添加文档
- 编写 OpenAPI/Swagger 规范
- 为多种语言创建代码示例
- 编写身份验证流程文档
- 构建开发者门户
- 改进现有 API 文档
- 设置交互式文档(Swagger UI、Redoc)
评论
支持 Markdown