温馨提示×

如何在Ubuntu上实现Swagger版本控制

小樊
42
2025-11-22 13:27:27
栏目: 智能运维

在Ubuntu上实现Swagger版本控制,可以遵循以下步骤:

1. 安装Swagger工具

首先,你需要安装Swagger工具。你可以使用npm(Node.js的包管理器)来安装Swagger。

sudo apt update
sudo apt install nodejs npm
sudo npm install -g swagger-jsdoc swagger-ui-express

2. 创建Swagger配置文件

在你的项目根目录下创建一个名为swagger.json的文件,用于定义你的API规范。

{
  "swagger": "2.0",
  "info": {
    "description": "API documentation for My API",
    "version": "1.0.0"
  },
  "host": "localhost:3000",
  "basePath": "/api",
  "schemes": [
    "http"
  ],
  "paths": {
    "/users": {
      "get": {
        "summary": "Get a list of users",
        "responses": {
          "200": {
            "description": "A JSON array of users"
          }
        }
      }
    }
  }
}

3. 创建Express应用

创建一个简单的Express应用,并集成Swagger UI。

mkdir my-api
cd my-api
npm init -y
npm install express

创建一个名为app.js的文件:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

const app = express();

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.get('/api/users', (req, res) => {
  res.json([
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Doe' }
  ]);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

4. 版本控制

为了实现版本控制,你可以在Swagger配置文件中添加版本信息,并在Express应用中处理不同版本的API。

4.1 更新Swagger配置文件

swagger.json中添加版本信息:

{
  "swagger": "2.0",
  "info": {
    "description": "API documentation for My API",
    "version": "1.0.0"
  },
  "host": "localhost:3000",
  "basePath": "/api/v1",
  "schemes": [
    "http"
  ],
  "paths": {
    "/users": {
      "get": {
        "summary": "Get a list of users",
        "responses": {
          "200": {
            "description": "A JSON array of users"
          }
        }
      }
    }
  }
}

4.2 更新Express应用

app.js中处理不同版本的API:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocumentV1 = require('./swagger.json');

const app = express();

app.use('/api-docs/v1', swaggerUi.serve, swaggerUi.setup(swaggerDocumentV1));

app.get('/api/v1/users', (req, res) => {
  res.json([
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Doe' }
  ]);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

5. 使用Git进行版本控制

将你的项目初始化为一个Git仓库,并进行版本控制:

git init
git add .
git commit -m "Initial commit with Swagger setup"

每次更新API或Swagger配置文件后,记得提交更改:

git add .
git commit -m "Update API version 1.1"

通过以上步骤,你可以在Ubuntu上实现Swagger版本控制,并使用Git进行版本管理。

0