在Linux上使用Swagger實現API版本管理,可以遵循以下步驟:
首先,確保你的Linux系統上已經安裝了Swagger。你可以使用npm(Node.js的包管理器)來安裝Swagger。
sudo npm install -g swagger-jsdoc swagger-ui-express
在你的項目根目錄下創建一個名為swagger.json
的文件,用于定義API的規范。這個文件應該包含所有版本的API信息。
{
"swagger": "2.0",
"info": {
"title": "API Documentation",
"description": "API Documentation for version 1.0",
"version": "1.0.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": [
"http"
],
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"responses": {
"200": {
"description": "A list of users"
}
}
}
}
}
}
為每個API版本創建單獨的Swagger配置文件。例如,如果你有版本1.1和1.2,你可以創建兩個文件:swagger-v1.1.json
和swagger-v1.2.json
。
{
"swagger": "2.0",
"info": {
"title": "API Documentation",
"description": "API Documentation for version 1.1",
"version": "1.1.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": [
"http"
],
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"responses": {
"200": {
"description": "A list of users"
}
}
}
}
}
}
{
"swagger": "2.0",
"info": {
"title": "API Documentation",
"description": "API Documentation for version 1.2",
"version": "1.2.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": [
"http"
],
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"responses": {
"200": {
"description": "A list of users"
}
}
}
}
}
}
在你的Express應用中集成Swagger,并根據請求的路徑動態加載相應的Swagger文檔。
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const app = express();
// Load Swagger docs
const swaggerOptions = {
swaggerDefinition: {
openapi: '3.0.0',
info: {
title: 'API Documentation',
description: 'API Documentation for version 1.0',
version: '1.0.0'
}
},
apis: ['./path/to/swagger-v1.1.json', './path/to/swagger-v1.2.json']
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
// API endpoints
app.get('/v1/users', (req, res) => {
res.json({ users: [] });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
啟動你的Express應用后,你可以通過瀏覽器訪問http://localhost:3000/api-docs
來查看Swagger UI,并測試不同版本的API。
通過以上步驟,你可以在Linux上使用Swagger實現API版本管理。關鍵在于為每個API版本創建單獨的Swagger配置文件,并在Express應用中動態加載這些配置文件。這樣,你就可以在一個統一的Swagger UI界面中管理和測試不同版本的API。