Debian與Swagger集成主要有以下兩種場景及方法:
安裝依賴
更新系統并安裝Node.js、npm及Swagger工具:
sudo apt update && sudo apt install nodejs npm
sudo npm install -g swagger-ui-express swagger-jsdoc
創建Swagger規范文件
在項目目錄生成swagger.json
或swagger.yaml
,定義API路徑、參數等,例如:
{
"swagger": "2.0",
"info": {"title": "Sample API", "version": "1.0.0"},
"paths": {
"/api/items": {
"get": {
"summary": "獲取所有項目",
"responses": {"200": {"description": "成功返回項目列表"}}
}
}
}
}
集成到Node.js應用
在Express應用中引入Swagger中間件:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => console.log('服務運行在 http://localhost:3000'));
訪問http://localhost:3000/api-docs
即可查看Swagger UI界面。
安裝框架及Swagger庫
sudo apt install python3-pip
pip3 install flask flasgger
配置Swagger
在Flask應用中添加Swagger配置:
from flask import Flask
from flasgger import Swagger
app = Flask(__name__)
swagger_config = {
"swagger_ui": True,
"specs": [{"endpoint": 'apispec_1', "route": '/swagger.json', "rule_filter": lambda rule: True}]
}
Swagger(app, config=swagger_config)
通過@swag_from
裝飾器為接口添加文檔注釋。
部署與訪問
運行Flask應用后,通過Nginx反向代理至http://服務器IP/swagger-ui
訪問文檔。
添加依賴
在pom.xml
中引入springdoc-openapi-ui
:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.15</version>
</dependency>
生成文檔
啟動Spring Boot應用后,訪問http://localhost:8080/swagger-ui.html
自動生成文檔。
swagger-ui-express
,其他語言需選擇對應SDK(如Python的flasgger
、Java的springdoc
)。swagger.yaml
或swagger.json
,可通過swagger-jsdoc
從代碼注釋自動生成。具體步驟可根據實際使用的編程語言和框架調整,參考官方文檔獲取最新細節。