在Debian系統上搭建Swagger UI,可以讓你方便地查看和測試API文檔。以下是一個基本的步驟指南:
首先,更新你的包列表并安裝必要的軟件包:
sudo apt update
sudo apt install -y nodejs npm
Swagger UI Express是一個基于Express的Swagger UI實現。你可以使用npm來安裝它:
sudo npm install -g swagger-ui-express
創建一個新的目錄來存放你的項目文件,并進入該目錄:
mkdir swagger-ui-demo
cd swagger-ui-demo
然后,創建一個名為app.js
的文件,并添加以下內容:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// Load Swagger document
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
在同一目錄下創建一個名為swagger.yaml
的文件,并添加你的API文檔。以下是一個簡單的示例:
swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI
version: '1.0.0'
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: List all users
responses:
'200':
description: An array of users
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
email:
type: string
format: email
現在,你可以運行你的Express應用:
node app.js
打開瀏覽器并訪問http://localhost:3000/api-docs
,你應該能夠看到Swagger UI界面,并且可以查看和測試你的API。
如果你希望將Swagger UI部署到生產環境中,可以使用Nginx作為反向代理。首先,安裝Nginx:
sudo apt install -y nginx
然后,創建一個Nginx配置文件:
sudo nano /etc/nginx/sites-available/swagger-ui
添加以下內容:
server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
啟用該配置文件:
sudo ln -s /etc/nginx/sites-available/swagger-ui /etc/nginx/sites-enabled
測試Nginx配置并重啟服務:
sudo nginx -t
sudo systemctl restart nginx
現在,你可以通過http://your_domain.com/api-docs
訪問Swagger UI。
通過以上步驟,你就可以在Debian系統上成功搭建Swagger UI了。