ubuntu

ubuntu如何自定义swagger UI

小樊
36
2025-07-07 07:04:45
栏目: 智能运维

在Ubuntu上自定义Swagger UI可以通过以下几种方法实现:

使用Node.js和Express集成Swagger UI

  1. 安装Node.js和npm
sudo apt update
sudo apt install nodejs npm
  1. 创建一个新的Node.js项目
mkdir swagger-ui-project
cd swagger-ui-project
npm init -y
  1. 安装Swagger UI Express
npm install swagger-ui-express
  1. 创建一个简单的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}`);
});
  1. 创建Swagger文档

在项目目录中创建一个名为 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
      name:
        type: string
  1. 运行应用

在项目文件夹中运行以下命令来启动应用:

node app.js
  1. 访问Swagger UI

在浏览器中访问 http://localhost:3000/api-docs,你应该能看到Swagger UI界面。

使用Docker安装Swagger UI

  1. 安装Docker
sudo apt update
sudo apt install docker.io
  1. 拉取Swagger UI Docker镜像
docker pull swaggerapi/swagger-ui-express
  1. 运行Swagger UI容器
docker run -p 8080:8080 swaggerapi/swagger-ui-express
  1. 访问Swagger UI

在浏览器中访问 http://localhost:8080,你应该能看到Swagger UI界面。

自定义Swagger UI样式

通过以上方法,你可以在Ubuntu上自定义Swagger界面,提升接口文档的可读性和美观度。

0
看了该问题的人还看了