温馨提示×

ubuntu下swagger如何测试

小樊
43
2025-11-24 12:16:27
栏目: 智能运维

Ubuntu下使用Swagger测试API的实用步骤

一 准备环境

  • 更新系统并安装 Node.jsnpm(Swagger Editor/UI 基于 Node 生态):
    • 命令:sudo apt update && sudo apt install -y nodejs npm
  • 可选:安装静态服务器 http-server,便于快速托管本地 Swagger UI/Editor
    • 命令:sudo npm install -g http-server
  • 说明:若已安装 Docker,也可直接拉取并运行 Swagger UI 容器,省去 Node 环境配置。

二 方式一 使用Docker运行Swagger UI并测试

  • 拉取镜像(示例使用 v4.15.5):
    • 命令:docker pull swaggerapi/swagger-ui:v4.15.5
  • 启动容器并挂载本地规范文件(当前目录含 swagger.yamlswagger.json):
    • 命令:docker run -d -p 38081:8080 -e SWAGGER_JSON=/app/swagger.yaml -v $(pwd):/app swaggerapi/swagger-ui:v4.15.5
  • 访问与测试:
    • 浏览器打开:http://localhost:38081/swagger-ui.html
    • 在页面中确认已加载你的 swagger.yaml/swagger.json,展开目标接口,点击 Try it out,填写参数后点击 Execute 查看响应。

三 方式二 在Node Express中集成Swagger UI并测试

  • 初始化项目并安装依赖:
    • 命令:mkdir swagger-demo && cd swagger-demo && npm init -y
    • 安装:npm install express swagger-ui-express yamljs
  • 创建 swagger.yaml(示例片段,注意 host/basePath/schemes 与实际服务一致):
    • 文件内容:
      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: /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
              format: int64
            name:
              type: string
      
  • 创建 index.js
    • 文件内容:
      const express = require('express');
      const swaggerUi = require('swagger-ui-express');
      const YAML = require('yamljs');
      
      const swaggerDocument = YAML.load('./swagger.yaml');
      const app = express();
      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} /api-docs`));
      
  • 启动服务并测试:
    • 启动:node index.js
    • 访问:http://localhost:3000/api-docs,在页面中点击 Try it out → Execute 测试接口。

四 常见问题与处理

  • 跨域问题(CORS):
    • 现象:浏览器控制台提示跨域。
    • 处理:在后端启用 CORS(如 cors 中间件),或将 Swagger UI 与后端同域部署;也可在开发阶段使用代理。
  • 认证问题:
    • 若接口需要 API Key/OAuth2,在 Swagger UI 的 Authorize 中填入凭据后再执行。
  • 生产环境安全:
    • 建议关闭或限制 /api-docs 访问,或通过 Nginx IP 白名单强制认证等手段保护文档。

0