温馨提示×

如何使用Swagger生成API文档

小樊
52
2025-10-04 04:17:45
栏目: 编程语言

如何使用Swagger生成API文档

Swagger(现称OpenAPI Specification)是一套用于设计、构建、文档化和使用RESTful API的工具集,支持自动生成交互式API文档。以下是分框架/语言的详细步骤,涵盖主流场景:

一、前置准备

  1. 安装Java环境(仅Java项目需要):
    Swagger依赖Java运行环境,通过以下命令安装OpenJDK 11(以Ubuntu为例):
    sudo apt update && sudo apt install openjdk-11-jdk
    
  2. 安装构建工具(Maven/Gradle):
    Java项目需配置Maven(pom.xml)或Gradle(build.gradle)以管理Swagger依赖。

二、Java项目(Spring Boot)步骤

1. 添加Swagger依赖

在项目的pom.xml(Maven)或build.gradle(Gradle)中添加以下依赖:

<!-- Springfox Swagger2(核心依赖) -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- Springfox Swagger UI(交互式文档界面) -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Gradle配置类似,将implementation替换为compile即可。

2. 配置Swagger扫描范围

创建一个配置类(如SwaggerConfig.java),用@Configuration@EnableSwagger2注解启用Swagger,并通过Docket Bean指定扫描的包路径:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 替换为你的Controller包路径
                .paths(PathSelectors.any()) // 扫描所有路径
                .build();
    }
}

可选配置:通过apiInfo()方法添加文档标题、描述、版本等信息,提升可读性。

3. 使用Swagger注解丰富文档

在Controller类和方法上添加Swagger注解,明确API的功能、参数、返回值等信息:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理", description = "用户相关操作接口") // 类级别注解,描述模块功能
public class UserController {

    @GetMapping("/{id}")
    @ApiOperation(value = "获取用户信息", notes = "根据用户ID查询详细信息") // 方法级别注解,描述接口功能
    public User getUserById(
            @PathVariable @ApiParam(value = "用户ID", required = true, example = "1") Long id) { // 参数注解,描述参数信息
        // 业务逻辑
        return userService.getUserById(id);
    }

    @PostMapping
    @ApiOperation(value = "创建用户", notes = "新增用户信息")
    public User createUser(@RequestBody @ApiParam(value = "用户对象", required = true) User user) {
        // 业务逻辑
        return userService.createUser(user);
    }
}

常用注解说明:

  • @Api:描述Controller模块的功能;
  • @ApiOperation:描述接口的具体功能;
  • @ApiParam:描述接口参数的详细信息(如是否必填、示例值);
  • @ApiResponse:描述接口的返回结果(如状态码、响应内容)。
4. 访问Swagger UI

启动Spring Boot应用后,在浏览器中访问以下URL(端口号根据项目配置调整):

http://localhost:8080/swagger-ui.html

进入后,可看到所有扫描到的API接口,点击接口名称可查看详细信息(如参数、返回值、请求示例),并支持TRY IT OUT功能直接测试接口。

三、其他框架/语言步骤

1. Node.js项目
  • 安装依赖
    npm install --save swagger-ui-express swagger-jsdoc
    
  • 配置Swagger
    创建swagger.js文件定义API规范,然后在app.js中加载:
    const express = require('express');
    const swaggerUi = require('swagger-ui-express');
    const swaggerJsdoc = require('swagger-jsdoc');
    
    const app = express();
    
    // 定义Swagger选项
    const options = {
      definition: {
        openapi: '3.0.0',
        info: {
          title: 'Node.js API文档',
          version: '1.0.0',
          description: 'API文档示例'
        }
      },
      apis: ['./routes/*.js'] // 指定API路由文件路径
    };
    
    const specs = swaggerJsdoc(options);
    
    // 挂载Swagger UI
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
    
    app.listen(3000, () => console.log('Server running on port 3000'));
    
  • 访问文档
    启动Node.js应用后,访问http://localhost:3000/api-docs即可查看文档。
2. Python(Flask)项目
  • 安装依赖
    pip install flask flask-swagger-ui
    
  • 配置Swagger
    在Flask应用中添加Swagger配置:
    from flask import Flask, jsonify
    from flask_swagger_ui import get_swaggerui_blueprint
    
    app = Flask(__name__)
    
    # Swagger UI配置
    SWAGGER_URL = '/api-docs'
    API_URL = '/static/swagger.json'
    
    swaggerui_blueprint = get_swaggerui_blueprint(
        SWAGGER_URL,
        API_URL,
        config={'app_name': "Flask API Docs"}
    )
    
    app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
    
    # 示例API
    @app.route('/api/users/<int:user_id>', methods=['GET'])
    def get_user(user_id):
        """获取用户信息
        ---
        parameters:
          - name: user_id
            in: path
            type: integer
            required: true
            description: 用户ID
        responses:
          200:
            description: 用户信息
            schema:
              type: object
              properties:
                id:
                  type: integer
                name:
                  type: string
        """
        return jsonify({'id': user_id, 'name': 'John Doe'})
    
    if __name__ == '__main__':
        app.run(debug=True)
    
  • 访问文档
    启动Flask应用后,访问http://localhost:5000/api-docs即可查看文档。

四、高级功能(可选)

  1. 自动化文档更新
    将Swagger配置集成到CI/CD流程(如Jenkins、GitLab CI),每次代码提交后自动生成最新文档。
  2. 权限管理
    通过Swagger的securityDefinitions配置(如OAuth2、API Key),限制文档访问权限。
  3. 微服务聚合
    使用API网关(如Spring Cloud Gateway、Kong)聚合所有微服务的Swagger文档,实现统一查看。

通过以上步骤,可根据项目框架快速生成并管理API文档,提升团队协作效率。

0