1. 安裝Swagger工具
在Ubuntu上配置Swagger前,需先安裝相關工具。若使用Node.js環境(推薦),先確保已安裝Node.js和npm:
sudo apt update
sudo apt install -y nodejs npm
再通過npm全局安裝Swagger UI和Swagger Editor:
sudo npm install -g swagger-ui-express swagger-editor-cli
若未使用Node.js,也可通過系統包管理器安裝(如sudo apt install swagger-jsdoc swagger-ui-express),但Node.js方式更靈活。
2. 編寫OpenAPI規范文件
Swagger文檔基于OpenAPI Specification(OAS),常用格式為swagger.yaml或swagger.json。以下是一個簡單的swagger.yaml示例:
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
description: A sample API for demonstration
servers:
- url: http://localhost:3000
description: Local development server
paths:
/users:
get:
summary: List all users
description: Retrieve a list of all users in the system
responses:
'200':
description: An array of user objects
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
description: The unique identifier of the user
name:
type: string
description: The full name of the user
required:
- id
- name
該文件定義了API的基本信息(標題、版本)、服務器地址、/users端點的GET操作及返回的用戶模型。
3. 集成Swagger到應用(以Express為例)
若項目使用Express框架,可通過swagger-ui-express中間件快速集成Swagger UI。首先安裝依賴:
sudo npm install --save express swagger-ui-express
然后在Express應用中配置Swagger:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.yaml'); // 引入規范文件
const app = express();
const PORT = process.env.PORT || 3000;
// 集成Swagger UI,訪問/api-docs查看文檔
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 示例路由(需與swagger.yaml中的路徑一致)
app.get('/users', (req, res) => {
res.json([
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
]);
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});
運行應用后,訪問http://localhost:3000/api-docs即可看到Swagger UI界面,包含API文檔和測試功能。
4. 可選:使用Swagger Editor編輯規范
若需更便捷地編輯Swagger規范,可使用Swagger Editor。通過npm全局安裝:
sudo npm install -g swagger-editor
啟動Editor后,訪問http://localhost:9000,即可在線編輯swagger.yaml或swagger.json文件,并實時預覽文檔效果。
5. 可選:Docker部署Swagger
若需要環境一致性,可使用Docker部署Swagger。首先編寫Dockerfile:
FROM node:16
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
然后構建并運行容器:
docker build -t swagger-ui .
docker run -d -p 3000:3000 --name swagger-container swagger-ui
訪問http://localhost:3000/api-docs即可查看Swagger UI。