在Linux上使用Swagger UI展示API文檔,可以按照以下步驟進行:
首先,你需要安裝Swagger UI。你可以選擇通過npm(Node.js的包管理器)來安裝,或者直接下載預構建的版本。
如果你還沒有安裝Node.js和npm,請先安裝它們。然后運行以下命令來全局安裝Swagger UI:
npm install -g swagger-ui-express
你也可以從Swagger UI的GitHub倉庫下載預構建的版本:
wget https://github.com/swagger-api/swagger-ui/archive/master.zip
unzip master.zip
cd swagger-ui-master
如果你選擇通過npm安裝Swagger UI,你可以創建一個簡單的Express應用來托管Swagger UI。
npm install express
創建一個名為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));
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: /
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
在終端中運行你的Express應用:
node app.js
打開瀏覽器并訪問http://localhost:3000/api-docs
,你應該能夠看到Swagger UI界面,并且可以瀏覽和測試你的API文檔。
如果你更喜歡使用Docker來部署Swagger UI,可以按照以下步驟進行:
創建一個名為Dockerfile
的文件,并添加以下內容:
FROM node:14
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package*.json ./
RUN npm install
# Bundle app source
COPY . .
EXPOSE 3000
CMD [ "node", "app.js" ]
在終端中運行以下命令來構建Docker鏡像:
docker build -t swagger-ui-app .
在終端中運行以下命令來啟動Docker容器:
docker run -p 3000:3000 swagger-ui-app
現在,你可以訪問http://localhost:3000/api-docs
來查看Swagger UI界面。
通過以上步驟,你可以在Linux上成功使用Swagger UI展示API文檔。