在Linux系統中集成Swagger UI,可以讓你更方便地查看和測試API文檔。以下是一個基本的步驟指南:
Swagger UI通常通過Node.js運行。首先,確保你的系統上已經安裝了Node.js和npm。
sudo apt update
sudo apt install nodejs npm
Swagger UI Express是一個用于Express應用的Swagger UI中間件。你可以使用npm來安裝它。
npm install swagger-ui-express
創建一個新的目錄并進入該目錄,然后初始化一個新的Node.js項目。
mkdir swagger-ui-example
cd swagger-ui-example
npm init -y
創建一個名為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 integration
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文檔。
通過以上步驟,你可以在Linux系統中集成Swagger UI,并使用它來查看和測試你的API文檔。你可以根據需要進一步自定義和擴展你的Swagger文檔和應用。