温馨提示×

如何在Debian上使用Swagger进行API测试

小樊
37
2025-12-28 11:07:00
栏目: 智能运维

在 Debian 上使用 Swagger 进行 API 测试

一 准备环境

  • 更新系统并安装基础工具与运行时:
    • sudo apt update && sudo apt upgrade -y
    • sudo apt install -y curl git
    • 选择其一安装运行时与工具链:
      • Node.js 方案:sudo apt install -y nodejs npm
      • Python 方案:sudo apt install -y python3 python3-pip
  • 可选:安装 Docker,便于快速运行 Swagger UI 容器:sudo apt install -y docker.io。

二 方式一 使用 Swagger UI 进行交互式测试

  • 本地集成到 Node.js 服务(适合已有后端)
    • 安装依赖:npm install -g swagger-ui-express [可选:yamljs]
    • 准备规范文件(示例为 OpenAPI 3.0,保存为 swagger.yaml):
      openapi: "3.0.0"
      info:
        title: Sample API
        version: "1.0.0"
      servers:
        - url: http://localhost:3000
      paths:
        /hello:
          get:
            summary: 返回问候语
            responses:
              '200':
                description: OK
                content:
                  application/json:
                    schema:
                      type: object
                      properties:
                        message:
                          type: string
      
    • 启动服务(app.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));
      app.get('/hello', (req, res) => res.json({ message: 'Hello, World!' }));
      app.listen(3000, () => console.log('Server on http://localhost:3000'));
      
    • 访问:打开浏览器访问 http://<服务器IP>:3000/api-docs,在页面中点击 Try it out 发起请求。
  • Docker 快速运行 Swagger UI(适合仅展示/调试远程或本地规范)
    • 拉取并运行:
      docker run --name swagger-ui -p 8080:8080 \
        -e SWAGGER_JSON=/spec/swagger.json \
        -v $PWD/swagger.yaml:/spec/swagger.json \
        swaggerapi/swagger-ui
      
    • 访问:http://<服务器IP>:8080,即可在 UI 中加载并测试你的规范。

三 方式二 自动化测试与持续集成

  • 基于规范生成客户端并编写测试(Python 示例)
    • 安装生成器:pip3 install swagger-codegen
    • 生成客户端:swagger-codegen generate -i swagger.yaml -l python -o ./client
    • 编写测试(test_api.py):
      import unittest
      from client.api.default_api import DefaultApi
      from client.configuration import Configuration
      
      class TestApi(unittest.TestCase):
          def setUp(self):
              config = Configuration()
              config.host = "http://localhost:3000"
              self.api = DefaultApi(config)
      
          def test_hello(self):
              resp = self.api.hello_get()
              self.assertEqual(resp[1], 200)
              self.assertIn("message", resp[0])
      
      if __name__ == '__main__':
          unittest.main()
      
    • 运行测试:python3 test_api.py
    • 集成 CI:在 GitLab CI/GitHub Actions 中安装依赖并执行测试脚本,实现提交即测。

四 常见问题与排查

  • 访问被拒绝或页面空白:确认服务监听 0.0.0.0 而非仅 127.0.0.1,并开放防火墙端口(如 ufw allow 3000/tcp)。
  • 规范加载失败:检查 swagger.yaml/swagger.json 语法与路径;Docker 方式需将本地文件正确挂载到容器内(示例已映射 -v $PWD/swagger.yaml:/spec/swagger.json)。
  • 接口 404/401:确认 servers.url 与后端服务地址一致;涉及鉴权请在 Swagger UI 的 Authorize 填入 Bearer TokenAPI Key 后再试。
  • 跨域问题:开发阶段在后端启用 CORS;或仅在内网/同域下使用 UI。

0