溫馨提示×

swagger UI在ubuntu上如何使用

小樊
59
2025-05-19 16:41:33
欄目: 智能運維

在Ubuntu上使用Swagger UI的步驟如下:

方法一:使用Docker

  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界面。

方法二:使用Node.js和Express

  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'
paths:
  /users:
    get:
      summary: List all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/definitions/User'
definitions:
  User:
    type: object
    properties:
      id:
        type: integer
      name:
        type: string
    required:
      - id
      - name
  1. 運行應用
node app.js
  1. 訪問Swagger UI

在瀏覽器中訪問 http://localhost:3000/api-docs,你應該能看到Swagger UI界面。

以上兩種方法可以幫助你在Ubuntu上集成Swagger UI,并查看和測試你的API文檔。

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