Redocly CLI 使用指南
强大的 OpenAPI 文档工具链
Redocly CLI 简介
Redocly CLI 是一个功能强大的命令行工具,用于:
- 📝 文档生成: 生成美观的 API 文档
- ✅ 规范验证: 检查 OpenAPI 规范的正确性
- 🔧 文件操作: 合并、拆分、打包 OpenAPI 文件
- 🎨 自定义主题: 定制文档外观
- 📊 质量检查: API 设计质量评分
安装和配置
安装方式
bash
# 使用 npm 安装(推荐)
npm install -g @redocly/cli
# 使用 yarn 安装
yarn global add @redocly/cli
# 使用 npx(无需安装)
npx @redocly/cli --version
# Docker 方式
docker run --rm -v $PWD:/spec redocly/cli lint openapi.yaml初始化配置
bash
# 创建配置文件
redocly init
# 生成的 redocly.yaml
apis:
main:
root: openapi.yaml
lint:
extends:
- recommended
rules:
no-unused-components: error
features.openapi:
generateCodeSamples:
languages:
- lang: curl
- lang: JavaScript
- lang: Python核心功能
1. 文档生成
基础文档生成
bash
# 生成 HTML 文档
redocly build-docs openapi.yaml -o api-docs.html
# 生成多页面文档
redocly build-docs openapi.yaml --split
# 使用自定义模板
redocly build-docs openapi.yaml --template custom-template.hbs高级配置
yaml
# redocly.yaml
apis:
main:
root: openapi.yaml
theme:
openapi:
generateCodeSamples:
languages:
- lang: curl
- lang: JavaScript
label: JS
- lang: Python
- lang: Java
- lang: Go
# 主题配置
theme:
colors:
primary:
main: '#1976d2'
success:
main: '#4caf50'
warning:
main: '#ff9800'
error:
main: '#f44336'
typography:
fontSize: '14px'
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif'
# 侧边栏配置
sidebar:
backgroundColor: '#f5f5f5'
textColor: '#333333'2. 规范验证(Lint)
基础验证
bash
# 验证单个文件
redocly lint openapi.yaml
# 验证多个文件
redocly lint api/**/*.yaml
# 使用特定规则集
redocly lint openapi.yaml --extends minimal
# 忽略特定规则
redocly lint openapi.yaml --skip-rule=operation-tags自定义规则
yaml
# redocly.yaml
lint:
extends:
- recommended
rules:
# 内置规则配置
info-contact: error
info-license: warning
operation-summary: error
operation-operationId-unique: error
operation-parameters-unique: error
path-not-include-query: error
# 自定义规则
operation-description:
severity: error
message: "操作必须包含描述"
tag-description:
severity: warning
message: "标签应该包含描述"
# 路径规则
path-keys-no-trailing-slash: error
path-parameters-defined: error
# 规则例外
decorators:
filter-out:
property: x-internal
value: true创建自定义规则
javascript
// rules/custom-rules.js
module.exports = {
rules: {
'chinese-description': {
description: '描述必须包含中文',
given: '$.paths.*.*',
then: {
field: 'description',
function: 'pattern',
functionOptions: {
match: '[\u4e00-\u9fa5]'
}
}
},
'response-example-required': {
description: '响应必须包含示例',
given: '$.paths.*.*.responses.*.content.*',
then: {
field: 'example',
function: 'defined'
}
}
}
};3. 文件操作
合并文件(Bundle)
bash
# 合并为单个文件
redocly bundle openapi.yaml -o bundled.yaml
# 解引用(展开 $ref)
redocly bundle openapi.yaml --dereferenced -o expanded.yaml
# 保留外部引用
redocly bundle openapi.yaml --keep-url-references -o bundled-external.yaml拆分文件(Split)
bash
# 拆分大文件
redocly split openapi.yaml --outDir ./split
# 拆分后的结构
split/
├── openapi.yaml # 主文件
├── paths/ # 路径定义
│ ├── users.yaml
│ └── orders.yaml
├── components/ # 组件定义
│ ├── schemas/
│ ├── parameters/
│ └── responses/
└── tags.yaml # 标签定义配置文件合并
yaml
# redocly.yaml
apis:
main:
root: openapi.yaml
bundle:
# 合并选项
dereferenced: false
# 外部引用处理
externalRefs:
- url: 'https://api.example.com/schemas/*'
bundle: false
# 文件包含顺序
files:
- ./info.yaml
- ./servers.yaml
- ./paths/**/*.yaml
- ./components/**/*.yaml4. 预览服务器
bash
# 启动预览服务器
redocly preview-docs openapi.yaml
# 指定端口
redocly preview-docs openapi.yaml --port 8080
# 热重载
redocly preview-docs openapi.yaml --watch
# 使用自定义主题
redocly preview-docs openapi.yaml --theme.openapi.theme.colors.primary.main=#ff5722高级功能
1. API 版本管理
yaml
# redocly.yaml
apis:
v1:
root: ./v1/openapi.yaml
output: ./docs/v1.html
v2:
root: ./v2/openapi.yaml
output: ./docs/v2.html
v3-beta:
root: ./v3/openapi.yaml
output: ./docs/v3-beta.html
# 生成所有版本文档
# redocly build-docs2. 多语言文档
yaml
# redocly.yaml
apis:
main:
root: openapi.yaml
i18n:
defaultLocale: zh-CN
locales:
- zh-CN
- en-US
translations:
zh-CN:
searchPlaceholder: "搜索..."
tryItOut: "试一试"
response: "响应"
requestBody: "请求体"
parameters: "参数"
responseExample: "响应示例"
en-US:
searchPlaceholder: "Search..."
tryItOut: "Try it out"
response: "Response"
requestBody: "Request body"
parameters: "Parameters"
responseExample: "Response example"3. 自定义插件
javascript
// plugins/custom-plugin.js
module.exports = {
id: 'custom-plugin',
decorators: {
oas3: {
'add-server-description': {
type: 'Server',
decorator: (server) => {
if (!server.description) {
server.description = `${server.url} 服务器`;
}
return server;
}
}
}
},
rules: {
'custom-rule': {
description: '自定义规则描述',
message: '{{error}}',
severity: 'error',
given: '$.paths.*.*',
then: {
function: 'customFunction'
}
}
},
functions: {
customFunction: (input, options) => {
// 自定义验证逻辑
if (someCondition) {
return [{ message: '验证失败' }];
}
return [];
}
}
};使用插件:
yaml
# redocly.yaml
plugins:
- './plugins/custom-plugin.js'
lint:
plugins:
- custom-plugin
rules:
custom-plugin/custom-rule: error4. CI/CD 集成
GitHub Actions
yaml
# .github/workflows/api-docs.yml
name: API Documentation
on:
push:
branches: [main]
paths:
- 'api/**'
- 'redocly.yaml'
jobs:
validate-and-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install Redocly CLI
run: npm install -g @redocly/cli
- name: Validate OpenAPI
run: redocly lint api/openapi.yaml
- name: Bundle API Spec
run: redocly bundle api/openapi.yaml -o dist/openapi.yaml
- name: Build Documentation
run: redocly build-docs dist/openapi.yaml -o dist/index.html
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./distGitLab CI
yaml
# .gitlab-ci.yml
stages:
- validate
- build
- deploy
validate:api:
stage: validate
image: node:18
script:
- npm install -g @redocly/cli
- redocly lint api/openapi.yaml
only:
changes:
- api/**
- redocly.yaml
build:docs:
stage: build
image: node:18
script:
- npm install -g @redocly/cli
- redocly bundle api/openapi.yaml -o public/openapi.yaml
- redocly build-docs public/openapi.yaml -o public/index.html
artifacts:
paths:
- public
only:
- main
pages:
stage: deploy
dependencies:
- build:docs
script:
- echo "Deploying to GitLab Pages"
artifacts:
paths:
- public
only:
- main5. 性能优化
yaml
# redocly.yaml
features.openapi:
# 懒加载配置
lazyRendering: true
# 搜索索引
searchIndex:
enabled: true
fields:
- summary
- description
- tags
# 代码示例生成
generateCodeSamples:
skipOptionalParameters: true
languages:
- lang: curl
options:
longFormat: false
followRedirect: true
trimRequestBody: true最佳实践
1. 项目结构
api-project/
├── api/
│ ├── openapi.yaml # 主规范文件
│ ├── info.yaml # API 信息
│ ├── servers.yaml # 服务器配置
│ ├── tags.yaml # 标签定义
│ ├── paths/ # 路径定义
│ │ ├── users.yaml
│ │ └── orders.yaml
│ └── components/ # 可重用组件
│ ├── schemas/
│ ├── parameters/
│ └── responses/
├── docs/ # 生成的文档
├── redocly.yaml # Redocly 配置
└── package.json # 项目配置2. 脚本配置
json
// package.json
{
"scripts": {
"lint": "redocly lint api/openapi.yaml",
"bundle": "redocly bundle api/openapi.yaml -o dist/openapi.yaml",
"build:docs": "redocly build-docs api/openapi.yaml -o docs/index.html",
"preview": "redocly preview-docs api/openapi.yaml",
"validate": "npm run lint && npm run bundle",
"split": "redocly split api/openapi.yaml --outDir ./split"
}
}3. 质量检查
bash
# 创建质量报告
redocly stats api/openapi.yaml
# 输出示例
OpenAPI Statistics:
Paths: 25
Operations: 87
Parameters: 156
Schemas: 43
Quality Score: A (95/100)
✓ All operations have summaries
✓ All operations have operationIds
✓ All schemas have descriptions
⚠ 3 operations missing examples
⚠ 2 parameters missing descriptions4. 团队协作
yaml
# redocly.yaml - 团队标准配置
lint:
extends:
- recommended
rules:
# 强制规则
info-contact: error
info-license: error
operation-summary: error
operation-description: error
operation-operationId: error
operation-operationId-unique: error
operation-tags: error
tag-description: error
# 参数规则
parameter-description: error
path-params-defined: error
# 响应规则
operation-success-response: error
operation-4xx-response: warning
# 安全规则
operation-security-defined: error
# 自定义消息
messages:
operation-summary: "操作必须有简短描述"
operation-description: "操作必须有详细说明"
parameter-description: "参数必须有描述"故障排除
常见问题
内存不足
bash# 增加 Node.js 内存限制 export NODE_OPTIONS="--max-old-space-size=4096" redocly build-docs large-api.yaml循环引用
yaml# 使用 bundleMaxDepth 限制深度 bundle: bundleMaxDepth: 10外部引用失败
yaml# 配置代理 http: proxy: http://proxy.company.com:8080
总结
Redocly CLI 提供了完整的 OpenAPI 文档工具链:
- 🎨 美观文档: 生成专业的 API 文档
- ✅ 质量保证: 强大的验证功能
- 🔧 灵活处理: 文件合并、拆分等操作
- 🚀 易于集成: 完美融入 CI/CD 流程
掌握 Redocly CLI,让 API 文档管理更加高效专业。