在Linux上利用Swagger进行API调试,通常涉及安装Swagger UI和Swagger Editor,配置相关依赖,并将API文档暴露给调试界面。以下是详细的步骤:
安装Node.js和npm:
sudo apt update
sudo apt install -y nodejs npm
下载并安装Swagger UI:
wget https://repo1.maven.org/maven2/io/springfox/springfox-swagger-ui/2.9.2/springfox-swagger-ui-2.9.2.html
unzip springfox-swagger-ui-2.9.2.html
sudo mv springfox-swagger-ui-2.9.2 /var/www/html/swagger-ui
配置Swagger UI(可选):
编辑 /var/www/html/swagger-ui/index.html
文件,找到以下行并进行修改:
script window.onload function () {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/api-docs",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
// End Swagger UI call region
window.ui = ui;
};
启动Web服务器(例如Apache或Nginx):
Apache:
sudo a2ensite default.conf
sudo systemctl restart apache2
Nginx:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.baksudo nano /etc/nginx/sites-available/default
修改 server
块中的 root
和 index
指令:
server {
listen 80 default_server;
listen [::]: 80 default_server;
root /var/www/html;
index index.html index.htm;
server_name _;
location / {
try_files $uri $uri/ /index.html;
}
}
保存并退出编辑器,然后重启Nginx:
sudo systemctl restart nginx
安装并启动Swagger Editor:
npm install -g swagger-editor
swagger editor http://localhost:9000
现在,你应该能够通过浏览器访问 http://your_server_ip/swagger-ui
和 http://your_server_ip:9000
来查看和使用 Swagger UI 和 Swagger Editor。
在Swagger中添加API调试和测试工具:
确保你已经安装了Swagger。如果还没有安装,可以使用以下命令进行安装:
npm install -g swagger
在你的项目中创建一个名为 swagger.json
的文件,用于描述你的API接口。
使用Swagger CLI生成API文档页面:
swagger project start my-api --host localhost --port 8080 --schemes http
启动Swagger UI服务器:
swagger project start my-api
打开浏览器,访问 http://localhost:8080
,你将看到Swagger UI界面,其中包含了你的API接口信息。在这里,你可以进行API的调试和测试。
通过以上步骤,你可以在Linux上成功安装和配置Swagger,从而进行API调试。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: linux部署gitlab要注意什么