在Ubuntu上搭建Swagger API文档的详细步骤
Swagger UI是基于Node.js的工具,因此需要先安装Node.js和npm(Node.js包管理器)。
打开终端,执行以下命令更新包列表并安装:
sudo apt update
sudo apt install nodejs npm
安装完成后,验证版本以确保安装成功:
node -v # 查看Node.js版本
npm -v # 查看npm版本
(注:建议使用Node.js LTS版本,避免兼容性问题。)
Swagger UI的核心功能通过swagger-ui-express(Express中间件)和yamljs(解析YAML文件)实现,需通过npm全局安装:
sudo npm install -g swagger-ui-express yamljs
安装完成后,可通过swagger-ui-express -h验证是否安装成功。
Swagger文档用于定义API的元数据(路径、参数、响应等),支持YAML或JSON格式。推荐使用YAML(更易读)。
在项目目录(如~/swagger-demo)下创建swagger.yaml文件,内容示例如下:
swagger: '2.0'
info:
title: Sample API
description: A demo API for Swagger UI integration
version: '1.0.0'
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: Get all users
description: Retrieve a list of all registered users
responses:
'200':
description: A JSON array of user objects
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
description: Unique user ID
name:
type: string
description: Full name of the user
email:
type: string
format: email
description: User's email address
(注:可根据实际API调整路径、参数和模型定义。)
通过Express框架托管Swagger UI,步骤如下:
mkdir ~/swagger-demo && cd ~/swagger-demo
npm init -y # 创建package.json文件
npm install express swagger-ui-express yamljs --save
index.jsconst express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// 加载Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// 托管Swagger UI,访问路径为/api-docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 示例API路由(可选,用于测试)
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
]);
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});
node index.js
启动后,终端会显示服务器地址和Swagger UI路径。
打开浏览器,访问http://localhost:3000/api-docs,即可看到Swagger UI界面。
/users)。若不想手动配置Node.js环境,可使用Docker快速部署:
sudo apt update
sudo apt install docker.io
sudo systemctl start docker
sudo systemctl enable docker
在项目根目录(~/swagger-demo)下创建Dockerfile,内容如下:
FROM node:18-alpine # 使用轻量级Alpine版Node.js
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
docker build -t swagger-demo .
docker run -d -p 3000:3000 --name swagger-container swagger-demo
访问http://localhost:3000/api-docs即可查看Swagger UI。
sudo(如sudo npm install -g swagger-ui-express)。index.js中修改PORT变量(如const PORT = 8080),并同步修改访问地址。swag init命令(需安装swag工具)从代码注释自动生成Swagger文档,减少手动维护成本。