温馨提示×

如何在Linux上利用Swagger进行API模拟

小樊
45
2026-01-08 10:13:09
栏目: 智能运维

在 Linux 上利用 Swagger 进行 API 模拟

一、方案总览

  • 使用容器快速起一个可交互的 Swagger EditorSwagger UI,导入你的 OpenAPI/Swagger 规范即可在页面中“Try it out”发起请求,适合演示、联调前的快速验证。
  • Node.js + Express 服务中集成 swagger-jsdoc + swagger-ui-express,既提供文档页面,也可挂载“模拟路由”(返回示例数据或简单逻辑),便于前端先行联调。
  • 若已有后端(如 Spring Boot),可直接引入 Swagger/Springfox 注解生成在线文档页面,用于手工测试与联调。

二、方案一 Docker 快速起 Editor 与 UI

  • 安装并启动 Docker(如尚未安装):sudo apt-get update && sudo apt-get install -y docker.io && sudo systemctl start docker && sudo systemctl enable docker
  • 启动 Swagger Editor(端口映射为 38080:8080):docker pull swaggerapi/swagger-editor:v4.6.0 && docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0
  • 启动 Swagger UI(端口映射为 38081:8080):docker pull swaggerapi/swagger-ui:v4.15.5 && docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
  • 使用方式:
    • 访问 http://localhost:38080 导入你的 swagger.json/swagger.yaml,在 Editor 中校验与调整规范。
    • 访问 http://localhost:38081,将页面中的 URL 指向你的规范文件(可使用已导出的文件 URL 或本机/内网可访问地址),即可在 UI 中“Try it out”发送请求进行模拟调用。
  • 提示:若需远程访问,请将容器端口映射为 0.0.0.0:38080 等,并确保防火墙放行对应端口。

三、方案二 Node Express 集成 Swagger UI 并做轻量模拟

  • 初始化项目与依赖:
    • mkdir swagger-mock && cd swagger-mock
    • npm init -y
    • npm install express swagger-jsdoc swagger-ui-express
  • 创建规范文件 swagger.json(示例为 OpenAPI 3.0.0):
    • {
      • “openapi”: “3.0.0”,
      • “info”: { “title”: “Sample API”, “version”: “1.0.0” },
      • “paths”: {
        • “/api/items”: {
          • “get”: {
            • “summary”: “Get a list of items”,
            • “responses”: {
              • “200”: {
                • “description”: “A JSON array of items”,
                • “content”: {
                  • “application/json”: {
                    • “schema”: { “type”: “array”, “items”: { “$ref”: “#/components/schemas/Item” } }
                  • }
                • }
              • }
            • }
          • },
          • “post”: {
            • “summary”: “Create a new item”,
            • “requestBody”: {
              • “required”: true,
              • “content”: {
                • “application/json”: {
                  • “schema”: { “$ref”: “#/components/schemas/Item” }
                • }
              • }
            • },
            • “responses”: { “201”: { “description”: “Item created” } }
          • }
        • }
      • },
      • “components”: {
        • “schemas”: {
          • “Item”: {
            • “type”: “object”,
            • “properties”: { “id”: { “type”: “integer” }, “name”: { “type”: “string” } },
            • “required”: [“id”, “name”]
          • }
        • }
      • }
    • }
  • 创建服务 server.js(挂载文档与“模拟路由”):
    • const express = require(‘express’); const swaggerJsDoc = require(‘swagger-jsdoc’); const swaggerUi = require(‘swagger-ui-express’); const app = express(); app.use(express.json());

      const swaggerOptions = { swaggerDefinition: { openapi: ‘3.0.0’, info: { title: ‘Sample API’, version: ‘1.0.0’ } }, apis: [‘./swagger.json’] }; const swaggerDocs = swaggerJsDoc(swaggerOptions);

      // 文档页面 app.use(‘/api-docs’, swaggerUi.serve, swaggerUi.setup(swaggerDocs));

      // 轻量“模拟”路由:返回示例数据 app.get(‘/api/items’, (req, res) => { res.json([ { id: 1, name: ‘Mock Item 1’ }, { id: 2, name: ‘Mock Item 2’ } ]); });

      app.post(‘/api/items’, (req, res) => { const item = req.body; // 简单回显并模拟 ID 生成 res.status(201).json({ id: Date.now(), …item }); });

      const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(Server running on port ${PORT}));

  • 启动与验证:node server.js,访问 http://localhost:3000/api-docs 查看文档,直接“Try it out”或调用 /api/items 验证模拟结果。

四、方案三 在 Spring Boot 项目中启用 Swagger 文档

  • 添加依赖(Maven,Springfox 2.x 示例):
    • - io.springfox - springfox-swagger2 - 2.9.2 - - - io.springfox - springfox-swagger-ui - 2.9.2 -
  • 配置(启用 Swagger 2):
    • @Configuration
      • @EnableSwagger2
      • public class SwaggerConfig {
        • @Bean
        • public Docket api() {
          • return new Docket(DocumentationType.SWAGGER_2)
            • .select()
            • .apis(RequestHandlerSelectors.any())
            • .paths(PathSelectors.any())
            • .build();
        • }
      • }
  • 访问文档:启动项目后打开 http://localhost:8080/swagger-ui.html,在页面中执行“Try it out”进行接口调用与验证。

五、实践建议

  • 规范先行:尽量使用 OpenAPI 3.0+,在 schema 中为响应与请求体补充 example,UI 会直接展示,便于“所见即所得”的模拟。
  • 区分“文档模拟”和“服务模拟”:Swagger UI 的“Try it out”会真实发请求;若后端未就绪,可在 Express 中增加“模拟路由”或在规范里使用 x-mock-response(部分工具支持)返回示例数据。
  • 安全与可达性:仅在内网或受控环境开放文档与模拟端口;远程访问时绑定 0.0.0.0 并配置防火墙/反向代理与鉴权。

0