在Linux环境下,实现Swagger API文档的版本控制可以通过以下步骤进行:

首先,确保你已经安装了Swagger工具。你可以使用npm来安装Swagger UI和Swagger Editor。
npm install -g swagger-ui-express swagger-editor-cli使用Swagger Editor创建你的API文档。你可以将文档保存为YAML或JSON格式。
swagger-editor-cli init my-api-docs将你的Swagger文档放入版本控制系统(如Git)中进行管理。
cd my-api-docsgit initgit add .git commit -m "Initial commit of API documentation"每次更新API文档时,修改相应的YAML或JSON文件,并提交更改。
# 修改文档vim api-spec.yaml# 提交更改git add api-spec.yamlgit commit -m "Update API documentation for version 1.1"使用Swagger UI Express来部署你的API文档。你可以将不同版本的文档部署在不同的路径下。
const express = require('express');const swaggerUi = require('swagger-ui-express');const YAML = require('yamljs');const app = express();// 加载不同版本的Swagger文档const swaggerDocumentV1 = YAML.load('./api-spec-v1.yaml');const swaggerDocumentV2 = YAML.load('./api-spec-v2.yaml');// 部署Swagger UIapp.use('/api-docs-v1', swaggerUi.serve, swaggerUi.setup(swaggerDocumentV1));app.use('/api-docs-v2', swaggerUi.serve, swaggerUi.setup(swaggerDocumentV2));const PORT = process.env.PORT || 3000;app.listen(PORT, () => {console.log(`Server is running on port ${PORT}`);});为了更好地管理不同版本的API文档,可以使用Git分支。
# 创建新分支git branch feature/v1.1# 切换到新分支git checkout feature/v1.1# 在新分支上进行修改和提交vim api-spec-v1.1.yamlgit add api-spec-v1.1.yamlgit commit -m "Update API documentation for version 1.1"# 合并分支到主分支git checkout maingit merge feature/v1.1你可以使用CI/CD工具(如Jenkins、GitLab CI)来自动化部署过程。每次提交更改到Git仓库时,自动触发部署脚本。
# .gitlab-ci.yml示例stages:- deploydeploy:stage: deployscript:- npm install- pm2 restart my-api-docsonly:- main通过以上步骤,你可以在Linux环境下实现Swagger API文档的版本控制,并且能够方便地管理和部署不同版本的API文档。