在Ubuntu系統中調試Swagger(現主要為OpenAPI規范),核心是通過本地工具鏈(如Swagger Editor/UI、Docker)或**集成開發環境(IDE)**驗證API文檔的正確性、測試接口響應,并排查配置或代碼問題。以下是具體步驟及技巧:
調試Swagger前需安裝以下工具:
sudo apt update
sudo apt install -y nodejs npm
安裝后驗證版本:node -v(需≥14.x)、npm -v(需≥6.x)。sudo apt update
sudo apt install -y docker.io
sudo systemctl start docker
sudo systemctl enable docker
Swagger Editor是可視化編輯與調試OpenAPI規范的工具,支持實時驗證語法、預覽文檔。
sudo npm install -g swagger-editor
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
tar -xvf v3.16.1.tar.gz
cd swagger-editor-3.16.1
swagger-editor
npm install
npm start
http://localhost:3000打開編輯器。swagger.yaml或swagger.json文件。Swagger UI是展示API文檔并測試接口的工具,支持“Explore”本地/遠程規范文件。
sudo npm install -g swagger-ui
docker pull swaggerapi/swagger-ui
docker run -d -p 8080:8080 -v /path/to/swagger.yaml:/usr/src/app/swagger.yaml swaggerapi/swagger-ui
(/path/to/swagger.yaml替換為本地規范文件路徑)swagger-ui
默認在http://localhost:8080啟動。http://localhost:8080訪問。http://localhost:3000/swagger.yaml,若Editor與UI在同一機器)或本地路徑,點擊“Explore”。userId=1),點擊“Execute”,查看響應結果(包括狀態碼、響應體、耗時)。若需調試Swagger生成的代碼(如Spring Boot項目中的Controller層),可使用Visual Studio Code(VS Code):
launch.json文件(點擊左側“Run and Debug”→“create a launch.json file”),添加以下配置(以Node.js項目為例):{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/app.js",
"skipFiles": ["<node_internals>/**"]
}
]
}
wwwroot/swagger-ui目錄下創建custom.js,編寫自定義函數(如自動授權):function authorizeSwagger() {
const token = localStorage.getItem('token');
if (token) {
window.swaggerUi.api.clientAuthorizations.add('Bearer', new SwaggerClient.ApiKeyAuthorization('Authorization', 'Bearer ' + token, 'header'));
}
}
通過InjectJavascript機制將腳本注入Swagger UI中間件,實現自動授權。http://localhost:8080無法打開),檢查防火墻設置:sudo ufw status
sudo ufw allow 8080/tcp
result.log),定位錯誤原因(如端口沖突、依賴缺失)。通過以上步驟,可在Ubuntu系統中完成Swagger的調試,覆蓋從規范編輯、接口測試到代碼級排查的全流程。若遇到具體問題,建議參考Swagger官方文檔或社區論壇(如Stack Overflow)獲取進一步幫助。