温馨提示×

如何自定义ubuntu上的Swagger UI

小樊
41
2025-12-27 22:44:36
栏目: 智能运维

要在Ubuntu上自定义Swagger UI,您可以遵循以下步骤:

  1. 安装Swagger UI: 首先,您需要在Ubuntu系统上安装Swagger UI。您可以通过npm(Node.js包管理器)来安装Swagger UI。如果您还没有安装Node.js,请访问https://nodejs.org/下载并安装。

    打开终端,运行以下命令来全局安装Swagger UI:

    npm install -g swagger-ui-express
    
  2. 创建一个简单的Express应用: 在您的Ubuntu系统上创建一个新的目录,用于存放您的Swagger UI项目。然后,在该目录中创建一个名为app.js的文件。

    app.js文件中,添加以下代码来创建一个简单的Express应用:

    const express = require('express');
    const swaggerUi = require('swagger-ui-express');
    const YAML = require('yamljs');
    
    const app = express();
    const port = process.env.PORT || 3000;
    
    // 读取Swagger JSON文件
    const swaggerDocument = YAML.load('./swagger.json');
    
    // 将Swagger文档添加到Express应用中
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    
    app.listen(port, () => {
      console.log(`Server is running at http://localhost:${port}`);
    });
    
  3. 添加Swagger JSON文件: 在项目目录中创建一个名为swagger.json的文件。在此文件中,您可以定义您的API规范。您可以使用Swagger Editor(https://editor.swagger.io/)来编写和验证您的API规范。

  4. 自定义Swagger UI: Swagger UI提供了许多选项来自定义外观和行为。您可以在app.js文件中设置这些选项。例如,要更改Swagger UI的主题,您可以使用以下代码:

    const customUiOptions = {
      deepLinking: true,
      presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIStandalonePreset
      ],
      plugins: [
        SwaggerUIBundle.plugins.DownloadUrl
      ],
      layout: "StandaloneLayout",
      theme: "swagger-ui-dark" // 更改主题为暗色
    };
    
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, customUiOptions));
    

    您可以在Swagger UI官方文档中找到更多关于自定义选项的信息:https://swagger.io/tools/swagger-ui/docs/customization-options/

  5. 运行Express应用: 在终端中,导航到项目目录并运行以下命令来启动Express应用:

    node app.js
    

    现在,您可以在浏览器中访问http://localhost:3000/api-docs来查看自定义的Swagger UI。

通过以上步骤,您可以在Ubuntu上自定义Swagger UI以满足您的需求。

0