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文檔的編輯、展示和在線測試,提升開發效率。