Swagger Editor和Swagger UI的安装依赖Node.js环境,需先通过以下命令安装:
sudo apt update
sudo apt install -y nodejs npm
# 验证安装
node -v # 查看Node.js版本
npm -v # 查看npm版本
Swagger Editor提供可视化的API文档编写和实时测试功能,支持本地部署或Docker运行:
方式一:npm全局安装+http-server启动
npm install -g swagger-editor
npm install -g http-server
# 进入Swagger Editor目录并启动
cd /usr/local/lib/node_modules/swagger-editor
http-server -p 8080
访问http://localhost:8080即可打开编辑器,默认加载Petstore示例API。
方式二:Docker运行
docker pull swaggerapi/swagger-editor
docker run -d -p 8888:8080 swaggerapi/swagger-editor
访问http://localhost:8888进入编辑器。
使用方法:
点击顶部菜单栏「File」→「Import」→「Open File」,选择本地的swagger.yaml或swagger.json文件;编辑完成后,可直接在界面上点击接口右侧的「Try it out」按钮,输入参数并执行测试,查看响应结果。
Swagger UI是官方推荐的API文档展示工具,支持在线测试接口,常见安装方式如下:
方式一:npm全局安装+Express集成
npm install -g swagger-ui-express express
mkdir swagger-ui-project && cd swagger-ui-project
npm init -y
# 创建server.js文件
echo "const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
const swaggerDocument = YAML.load('./swagger.yaml'); // 加载本地API文档
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = 3000;
app.listen(PORT, () => console.log(\`Server running on http://localhost:\${PORT}\`));" > server.js
# 启动服务
node server.js
访问http://localhost:3000/api-docs即可查看Swagger UI界面。
方式二:Docker运行
docker pull swaggerapi/swagger-ui
mkdir swagger-docs && cp /path/to/your/swagger.yaml swagger-docs/
docker run -d -p 8080:8080 -e SWAGGER_JSON=/app/swagger.yaml -v $(pwd)/swagger-docs:/app swaggerapi/swagger-ui
访问http://localhost:8080,页面会自动加载swagger.yaml文件。
方式三:直接下载源码运行
git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
npm start
访问http://localhost:3000/swagger-ui/index.html,修改dist/index.html中的url字段(指向你的API文档地址)即可自定义文档来源。
无论是Swagger Editor还是Swagger UI,都需要指定API文档的位置:
https://petstore.swagger.io/v2/swagger.json,可通过编辑index.html文件修改defaultDocument变量,指向本地或远程文档。-e SWAGGER_JSON或server.js中的YAML.load('./swagger.yaml'))。启动Swagger UI后,按照以下步骤进行接口测试:
http://localhost:8080/v2/api-docs)或选择本地swagger.yaml文件,点击「Import」。/users/get),点击展开。-p 8081:8080)。/v2/api-docs)。chmod -R 777 swagger-docs)。通过以上步骤,即可在Ubuntu系统上使用Swagger完成API文档的编辑、展示和在线测试,提升开发效率。