在Ubuntu上使用Swagger进行API版本控制,可以通过以下步骤实现:
sudo apt-get update
sudo apt-get install swagger-ui-express
app.js的文件,并添加以下代码以创建一个简单的Express应用:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
// 读取Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
// 使用swagger-ui-express中间件
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 启动服务器
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
swagger.yaml的文件,并编写你的API文档。为了实现版本控制,可以在paths对象中为每个版本的API创建一个单独的键。例如:swagger: '2.0'
info:
title: API Versioning Example
description: An example of API versioning with Swagger on Ubuntu
version: '1.0.0'
host: localhost:3000
basePath: /v1
schemes:
- http
paths:
/users:
get:
summary: Get list of users
responses:
'200':
description: A JSON array of users
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
在这个例子中,我们将API的基本路径设置为/v1,并为/users端点定义了一个GET请求。
node app.js
访问Swagger UI:在浏览器中访问http://localhost:3000/api-docs,你应该能看到Swagger UI界面,其中显示了你定义的API文档。
添加新版本:要添加新版本的API,只需在swagger.yaml文件中创建一个新的基本路径(例如/v2),并为新版本的端点添加相应的定义。然后,更新app.js中的basePath以指向新版本的基本路径。
通过这种方式,你可以在同一个应用中使用Swagger对多个API版本进行版本控制。