温馨提示×

Debian Swagger如何实现API文档自动生成

小樊
35
2025-11-02 19:04:16
栏目: 智能运维

Debian系统下实现Swagger API文档自动生成的步骤

1. 安装必要工具

在Debian系统上,根据开发语言(Java/Node.js/Python/PHP等)安装对应的Swagger工具链:

  • 通用工具:安装curlwget用于下载工具包,unzip用于解压文件。
    sudo apt update && sudo apt install -y curl wget unzip
    
  • Java项目:安装JDK(≥11)、Maven/Gradle(依赖管理)。
    sudo apt install -y openjdk-11-jdk maven gradle
    
  • Node.js项目:安装Node.js、npm及Swagger命令行工具。
    sudo apt install -y nodejs npm
    sudo npm install -g swagger-jsdoc swagger-ui-express
    
  • Python项目:创建虚拟环境并安装Flasgger(Flask)或drf-yasg(Django)。
    sudo apt install -y python3-pip python3-venv
    python3 -m venv swagger-env && source swagger-env/bin/activate
    pip install flasgger  # Flask框架
    # 或 pip install drf-yasg  # Django框架
    

2. 编写OpenAPI规范文件

使用YAML或JSON格式定义API结构(推荐OpenAPI 3.0+),描述端点、参数、响应模型等。例如:

  • 基础YAML示例(swagger.yaml
    openapi: 3.0.0
    info:
      title: Sample API
      version: 1.0.0
      description: A demo API for Swagger documentation
    servers:
      - url: http://localhost:8080/api
    paths:
      /users:
        get:
          summary: Get all users
          responses:
            '200':
              description: A list of users
              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
    

3. 集成Swagger到项目

根据开发框架将Swagger嵌入应用,实现文档与代码同步:

  • Java(Spring Boot)
    添加Springfox依赖(pom.xml):
    <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();
      }
    }
    
  • Node.js(Express)
    在应用中引入Swagger UI和jsdoc:
    const express = require('express');
    const swaggerUi = require('swagger-ui-express');
    const swaggerDocument = require('./swagger.json');
    const app = express();
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    app.listen(3000, () => console.log('Server running on port 3000'));
    
  • Python(Flask)
    使用Flasgger装饰器生成文档:
    from flask import Flask, jsonify
    from flasgger import Swagger
    
    app = Flask(__name__)
    app.config['SWAGGER'] = {'title': 'Sample API', 'uiversion': 3}
    Swagger(app)
    
    @app.route('/api/v1/users')
    def get_users():
      """Get all users
      ---
      responses:
        200:
          description: A list of users
          schema:
            type: array
            items:
              type: object
              properties:
                id:
                  type: integer
                name:
                  type: string
      """
      return jsonify([{'id': 1, 'name': 'John'}])
    

4. 自动化生成与部署

将Swagger集成到项目构建流程,实现文档自动生成:

  • Maven项目:添加OpenAPI生成器插件(pom.xml):
    <build>
      <plugins>
        <plugin>
          <groupId>org.openapitools</groupId>
          <artifactId>openapi-generator-maven-plugin</artifactId>
          <version>6.6.0</version>
          <executions>
            <execution>
              <goals>
                <goal>generate</goal>
              </goals>
              <configuration>
                <inputSpec>${project.basedir}/src/main/resources/swagger.yaml</inputSpec>
                <generatorName>spring</generatorName>
                <output>${project.build.directory}/generated-sources</output>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>
    
  • Shell脚本:编写自动化脚本(generate-swagger.sh):
    #!/bin/bash
    API_SPEC="./swagger.yaml"
    OUTPUT_DIR="./generated-docs"
    SWAGGER_CLI="swagger-codegen-cli-3.0.29.jar"
    
    # 下载Swagger CLI(若未安装)
    if [ ! -f "$SWAGGER_CLI" ]; then
      wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.29/swagger-codegen-cli-3.0.29.jar -O $SWAGGER_CLI
    fi
    
    # 生成HTML文档
    java -jar $SWAGGER_CLI generate \
      -i $API_SPEC \
      -l html2 \
      -o $OUTPUT_DIR
    
    echo "Swagger文档生成完成:$OUTPUT_DIR"
    
    赋予执行权限并运行:
    chmod +x generate-swagger.sh
    ./generate-swagger.sh
    

5. 访问Swagger UI

启动应用后,通过浏览器访问Swagger UI界面:

  • Spring Boothttp://localhost:8080/swagger-ui.html
  • Expresshttp://localhost:3000/api-docs
  • Flaskhttp://localhost:5000/apidocs

通过上述步骤,即可在Debian系统上实现Swagger API文档的自动生成与维护,确保文档与代码同步更新。

0