溫馨提示×

swagger怎樣在ubuntu運行

小樊
43
2025-08-07 04:44:33
欄目: 智能運維

要在Ubuntu上運行Swagger,您需要遵循以下步驟:

  1. 安裝Node.js和npm(Node.js包管理器): 如果您還沒有安裝Node.js和npm,請訪問https://nodejs.org/en/download/package-manager/ubuntu/ 下載并安裝適用于Ubuntu的Node.js和npm。

  2. 全局安裝Swagger UI Express: 打開終端,然后運行以下命令以全局安裝Swagger UI Express:

    npm install -g swagger-ui-express
    
  3. 創建一個簡單的Swagger應用: 在您的開發目錄中創建一個名為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-ui-express中間件
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    
    // 啟動服務器
    app.listen(port, () => {
      console.log(`Server is running at http://localhost:${port}`);
    });
    
  4. 創建一個Swagger文檔: 在您的開發目錄中創建一個名為swagger.yaml的新文件,并添加以下示例Swagger文檔:

    swagger: '2.0'
    info:
      title: Sample API
      description: A sample API to demonstrate Swagger UI Express
      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
    
  5. 運行Swagger應用: 在終端中,導航到包含app.js文件的目錄,然后運行以下命令啟動應用:

    node app.js
    
  6. 訪問Swagger UI: 打開瀏覽器,訪問http://localhost:3000/api-docs。您應該看到Swagger UI界面,其中顯示了您的API文檔。

現在您已經在Ubuntu上成功運行了Swagger。您可以繼續開發和擴展您的API以及相應的Swagger文檔。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女