要在Ubuntu上运行Swagger UI,您需要遵循以下步骤:
安装Node.js和npm(Node.js包管理器): 打开终端并运行以下命令来安装Node.js和npm:
sudo apt update
sudo apt install nodejs npm
安装Swagger UI: 使用npm全局安装Swagger UI:
sudo npm install -g swagger-ui-express
创建一个简单的Express应用:
在您的主目录中创建一个名为app.js的新文件,并添加以下内容:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
const port = process.env.PORT || 3000;
// 读取Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
// 将Swagger文档添加到Express应用中
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 启动Express服务器
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
创建Swagger文档:
在您的主目录中创建一个名为swagger.yaml的新文件,并添加您的API文档。这是一个简单的示例:
swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI on Ubuntu
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
email:
type: string
format: email
运行应用:
在终端中,导航到包含app.js文件的目录,然后运行以下命令启动应用:
node app.js
访问Swagger UI:
打开浏览器并访问http://localhost:3000/api-docs。您应该看到Swagger UI界面,其中显示了您的API文档。
注意:在实际项目中,您可能需要根据您的API需求调整Swagger文档。