在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版本進行版本控制。