Swagger UI及配套工具依赖Node.js环境,首先需安装Node.js和npm(Node.js包管理器):
sudo apt update
sudo apt install nodejs npm
安装完成后,通过node -v和npm -v验证安装是否成功。
Swagger UI是可视化测试API的核心工具,以下是两种常见安装方式:
sudo npm install -g swagger-ui-express
此命令会将Swagger UI安装到系统全局环境,后续可通过命令行快速启动。
若系统已安装Docker,可直接拉取Swagger UI镜像并运行容器:
sudo apt update
sudo apt install docker.io # 若未安装Docker
docker pull swaggerapi/swagger-ui:v4.15.5 # 拉取最新镜像
docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5 # 运行容器(映射端口38081到容器8080)
容器启动后,无需额外配置即可通过浏览器访问。
要让Swagger UI显示并测试你的API,需提供Swagger规范文件(swagger.yaml或swagger.json)。以下是两种配置场景:
若通过npm安装,启动Swagger UI后,在浏览器访问http://localhost:8081(默认端口),点击页面顶部的Explore按钮,输入你的Swagger文档URL(如http://your-api-server/v2/api-docs)或上传本地swagger.yaml文件,即可加载API文档。
若你有Express后端项目,可将Swagger UI集成到项目中,实现文档与API服务联动:
mkdir swagger-demo && cd swagger-demo
npm init -y
npm install express swagger-ui-express yamljs
index.js文件,配置Swagger UI:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
const swaggerDocument = YAML.load('./swagger.yaml'); // 加载本地swagger.yaml文件
// 将Swagger UI挂载到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/api-docs`);
});
swagger.yaml文件(示例):swagger: '2.0'
info:
title: Sample API
version: 1.0.0
description: A demo API for Swagger testing
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: Get all users
responses:
'200':
description: A list of users
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string
node index.js
http://localhost:3000/api-docs,即可看到自动生成的文档。无论通过哪种方式配置,加载文档后即可开始测试:
/users的GET方法),点击展开。/users接口可能需要limit参数)。cors中间件),避免跨域请求被拦截。Bearer xxx),否则无法正常测试受保护接口。swagger.yaml文件后,需重启Express应用或刷新Swagger UI页面,使变更生效。通过以上步骤,你可在Ubuntu上快速使用Swagger进行API测试,实现文档可视化与接口调试的联动。