温馨提示×

如何在Linux系统上使用Swagger进行API设计

小樊
44
2025-11-20 09:07:21
栏目: 智能运维

在 Linux 上使用 Swagger 进行 API 设计的实操指南

一 环境准备与工具选择

  • 在 Linux 上进行 API 设计,常用工具包括:Swagger Editor(在线/本地编写与校验 OpenAPI 规范)、Swagger UI(交互式文档与调试)、以及代码生成工具(从规范生成服务端存根或客户端 SDK)。实际工作中“Swagger”多指工具生态,规范名称为 OpenAPI Specification(OAS),建议使用 OAS 3.x 版本以获得更好的生态支持与可维护性。

二 安装与启动 Editor 和 UI

  • 方式一 Docker 快速启动(推荐)
    • 拉取并运行容器(建议固定版本以便维护):
      • Editor:docker run -d -p 8080:8080 swaggerapi/swagger-editor:v4.6.0
      • UI:docker run -d -p 8081:8080 swaggerapi/swagger-ui:v4.15.5
    • 访问地址:Editor 为 http://<服务器IP>:8080,UI 为 http://<服务器IP>:8081。如需更新,停止旧容器、拉取新镜像并重新运行即可。
  • 方式二 本机 Node.js 手动部署
    • 安装 Node.js 与 npm(以 Ubuntu/Debian 为例):sudo apt update && sudo apt install -y nodejs npm
    • 启动 Editor(内置静态服务):
      • 下载并解压 swagger-editor 包,进入目录后执行:npm install && npm start(默认端口 9000,访问 http://localhost:9000
    • 启动 UI(两种常见做法):
      • 使用官方包:下载并解压 swagger-ui,npm install && npm start(常见端口 3000,访问 http://localhost:3000
      • 作为静态站点托管:将 swagger-ui 的 dist 目录内容拷贝到你的静态站点目录(如 public),通过 Nginx/Apache 提供服务,并在 UI 配置中指向你的 openapi.yaml/swagger.json

三 编写 OpenAPI 规范与本地验证

  • 基本结构与示例(OAS 3.0):
    • 新建文件 openapi.yaml
      openapi: 3.0.0
      info:
        title: Sample API
        version: 1.0.0
      servers:
        - url: http://localhost:3000/api
      paths:
        /users:
          get:
            summary: 获取用户列表
            responses:
              '200':
                description: OK
                content:
                  application/json:
                    schema:
                      type: array
                      items:
                        $ref: '#/components/schemas/User'
      components:
        schemas:
          User:
            type: object
            properties:
              id:
                type: integer
                format: int64
              name:
                type: string
              email:
                type: string
                format: email
      
    • Swagger Editor 中打开/粘贴该文件,利用其实时校验与预览功能检查语法与结构;修正错误后导出 JSON/YAML 供后续使用。

四 集成到后端项目与自动化交付

  • 集成到 Node.js/Express
    • 使用 swagger-ui-express 托管文档并加载本地规范:
      const express = require('express');
      const swaggerUi = require('swagger-ui-express');
      const YAML = require('yamljs');
      const app = express();
      const swaggerDocument = YAML.load('./openapi.yaml');
      app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
      app.listen(3000, () => console.log('Server on 3000'));
      
    • 访问 http://localhost:3000/api-docs 查看交互式文档。
  • 集成到 Spring Boot(Springfox,适用于传统项目)
    • 添加依赖(Maven):
      <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
      </dependency>
      <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
      </dependency>
      
    • 配置类启用 Swagger(示例):
      @Configuration
      @EnableSwagger2
      public class SwaggerConfig {
        @Bean
        public Docket api() {
          return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
            .paths(PathSelectors.any())
            .build();
        }
      }
      
    • 启动后访问 http://localhost:8080/swagger-ui.html
  • 代码生成与自动化
    • 使用 Swagger Codegen 从规范生成客户端/服务端代码(示例:生成 Java 客户端):
      • 安装:sudo snap install swagger-codegen(或使用包管理器/下载可执行文件)
      • 生成:swagger-codegen generate -i openapi.yaml -l java -o ./generated/java-client
    • 结合 Jenkins/GitLab CIAnsible 将“拉取规范→校验→生成→部署文档站点”流程纳入 CI/CD,保证多环境一致与自动更新。

0