Swagger 文档工具介绍及Spring boot 项目集成案例

Swagger 是一款开源的 API 文档工具,通过生成可视化文档、自动生成客户端 SDK 等功能,使得 API 的设计、开发、测试等阶段更加高效和规范化。

一. Swagger 概述

Swagger 是由 Tony Tam 创建的一个开源工具集,旨在帮助开发者设计、构建、记录和使用 RESTful API。Swagger 提供了一组工具,使得我们可以创造性的深入到 API 的设计、开发和测试阶段中,从而提高 API 的设计质量和开发效率。

Swagger 的核心是 Swagger Specification,这是一种定义 API 的标准格式,以 OpenAPI Specification(前身是 Swagger Specification)的形式存在。Swagger Specification 中定义了 API 的基本信息、路径、HTTP 方法、参数、响应等内容,以及其他关于 API 的详细描述。

Swagger 还提供了一些工具,用来解析 Swagger Specification,并生成交互式的 API 文档以及客户端 SDK。

二. Swagger 功能

Swagger 的主要功能可以分为以下几个方面:

2.1 自动生成 API 文档

Swagger 可以通过解析代码中的注解来自动生成 API 文档,包括 API 的请求路径、HTTP 方法、参数、响应等信息,并以交互式的方式展现给用户。

2.2 支持多种数据格式

Swagger 支持多种数据格式,包括 JSON、XML 和 YAML 等。通过支持这些数据格式,使得 API 的描述和文档更加易于阅读和维护。

2.3 自动生成客户端 SDK

Swagger 可以根据 API 的规范自动生成客户端 SDK,包括 Java、Python、JavaScript 等多个语言。这使得客户端开发人员可以更加快速、准确地使用 API,并且避免了手动编写客户端代码的错误和繁琐。

2.4 兼容性

Swagger 与 RESTful API 兼容,同时也支持其他 Web 服务,如 SOAP 和 XML-RPC。这使得 Swagger 更加通用,可以适用于多种 Web 服务。

三. 基于Sprnig Boot 与 Swagger 的简单示例

在基于 Spring Boot 的项目中,使用 Swagger 只需要进行简单的配置即可。下面将给出一个基于 Spring Boot 的 Swagger 使用示例。

3.1 添加 Maven 依赖

首先,在项目的 pom.xml 文件中添加 Swagger 和 Swagger UI 的 Maven 依赖:

<!--Swagger依赖-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    <scope>compile</scope>
</dependency>

<!--Swagger-UI依赖-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
    <scope>compile</scope>
</dependency>

3.2 添加 Swagger 配置

在 Spring Boot 项目中,可以通过添加一个配置类来配置 Swagger:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    
    @Bean
    public Docket api() {
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder()
                .title("SpringBoot-Swagger Demo")
                .description("This is a demo for SpringBoot-Swagger")
                .version("1.0")
                .build();
    }
}

上述代码中,通过 @Configuration 注解声明该类为配置类,并通过 @EnableSwagger2 注解启用 Swagger。在 Docketapi() 方法中,配置了 API 扫描的基础包路径、API 扫描的路径、Swagger Specification 的版本以及文档信息等。

3.3 写一个方法,并且加上相关注解

@PostMapping("/login")
@ApiOperation(value = "用户登录", notes = "通过用户名和密码进行身份验证")
@ApiImplicitParams({
    
    
    @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "query"),
    @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query")
})
public ResponseEntity<String> login(
        @RequestParam("username") String username,
        @RequestParam("password") String password) {
    
    
    if (userService.login(username, password)) {
    
    
        return ResponseEntity.ok("登录成功");
    } else {
    
    
        throw new ApiException(ErrorCode.USER_LOGIN_FAILED);
    }
}

3.4 测试 API 文档

完成上述配置后,在项目启动后访问 http://localhost:8080/swagger-ui.html 就可以看到生成的 API 文档了。

在这个页面中,我们可以浏览和测试所有定义的接口。我们可以单击每个接口并查看其请求和响应的参数、返回值类型和格式等信息。同时,我们还可以在这里测试 API,而无需使用 Postman 或其他工具。

四. 使用注解定义 API

使用注解是最常用的方式来定义 API,通过注解可以很方便地将 API 的描述和实现代码集成在一起。Swagger 提供了多种注解,
包括 @Api@ApiOperation@ApiParam@ApiResponse@ApiImplicitParam@ApiImplicitParams@RequestBody 等注解,以及一些其他常用注解,如 @ApiIgnore@ApiModel@ApiModelProperty@ApiResponses@ApiParamImplicit@ApiParamImplicitSet 等。下面我们将分别介绍这些注解的使用方法和示例。

在使用 Swagger 描述 API 时,通常需要使用以下几个注解。

4.1 @Api

该注解用于描述整个 API 定义信息,并提供基本信息,例如版本、标题、描述、协议等。通常在应用入口中使用该注解。

@Api(value = "UserController", tags = {
    
    "用户操作接口"})
@RestController
@RequestMapping("/api")
public class UserController {
    
    
    // ...
}

上面的代码中,我们使用了 @Api 注解来定义 UserController 类,指定了值为 “UserController”,标签为 “用户操作接口”。

4.12 @ApiOperation

该注解用于描述 API 操作信息,例如描述、HTTP 方法、URL 等。通常在方法上使用。

@PostMapping("/user")
@ApiOperation(value = "创建新用户", notes = "根据 User 对象创建新用户")
@ApiResponses(value = {
    
    
        @ApiResponse(code = 200, message = "请求成功"),
        @ApiResponse(code = 400, message = "请求参数错误"),
        @ApiResponse(code = 409, message = "用户已存在")
})
public ResponseEntity<User> createUser(@ApiParam(name = "user", value = "用户对象", required = true) @RequestBody User user) {
    
    
    if (userService.createUser(user) != null) {
    
    
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    } else {
    
    
        throw new ApiException(ErrorCode.USER_ALREADY_EXISTS);
    }
}

上面的代码中,我们使用了 @ApiOperation 注解来定义 createUser() 方法的操作信息,指定了值为 “创建新用户”,描述为 “根据 User 对象创建新用户”。

4.3 @ApiParam

该注解用于描述参数信息,例如名称、数据类型、必填、描述信息等。通常在方法参数上使用。

@PostMapping("/user")
public ResponseEntity<User> createUser(@ApiParam(name = "user", value = "用户对象", required = true) @RequestBody User user)

上面的代码中,我们使用了 @ApiParam 注解来描述请求体参数 user,指定了名称为 “user”,取值为 “用户对象”,必填,并作为 createUser() 的一个参数。

4.4 @ApiResponse

该注解用于描述 API 响应信息,例如状态码、描述信息、响应模型等。通常在方法返回值类型上使用。

@ApiResponses(value = {
    
    
        @ApiResponse(code = 200, message = "请求成功"),
        @ApiResponse(code = 400, message = "请求参数错误"),
        @ApiResponse(code = 409, message = "用户已存在")
})
public ResponseEntity<User> createUser(@RequestBody User user) {
    
    
    // ...
}

上面的代码中,我们使用了 @ApiResponse 注解来描述响应信息,指定了状态码为 200、400、409,对应的描述信息为 “请求成功”、“请求参数错误” 和 “用户已存在”。

4.5 @ApiImplicitParam@ApiImplicitParams

这两个注解用于描述请求参数信息,例如名称、数据类型、必填、描述信息等。通常在方法上使用。

@PostMapping("/user")
@ApiImplicitParams({
    
    
        @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query")
})
public ResponseEntity<User> createUser(String username, String password) {
    
    
    // ...
}

上面的代码中,我们使用了 @ApiImplicitParam 注解来描述请求参数 usernamepassword,指定了名称、取值、必填、数据类型。

4.6 @RequestBody

该注解用于描述请求体参数信息,例如名称、数据类型、必填、描述信息等。通常在方法参数上使用。

@PostMapping("/user")
public ResponseEntity<User> createUser(@RequestBody User user)

上面的代码中,我们使用了 @RequestBody 注解来描述请求体参数,作为 createUser() 方法的一个参数。

4.7 @ApiIgnore

该注解用于忽略指定项(类、方法、参数)的 API 文档生成,适用于那些不需要对外暴露的接口或属性。

@ApiIgnore
public class IgnoreMe {
    
    
    // ...
}

上面的代码中,我们使用了 @ApiIgnore 注解来忽略 IgnoreMe 类,不会在生成的 API 文档中出现。

4.8 @ApiModel

该注解用于为数据模型添加描述信息,包括名称、描述、属性等。

@ApiModel(value = "User", description = "用户对象")
@Data
public class User {
    
    
    @ApiModelProperty(value = "用户ID", example = "1")
    private Long id;
    @ApiModelProperty(value = "用户名", required = true)
    private String username;
    @ApiModelProperty(value = "密码", required = true, example = "123456")
    private String password;
}

上面的代码中,我们使用了 @ApiModel 注解来为 User 类添加描述信息,指定了名称为 “User”,描述为 “用户对象”。

4.9 @ApiModelProperty

该注解用于为数据模型中的属性添加描述信息,包括名称、描述、数据类型、默认值等。

@Data
@ApiModel(value = "User", description = "用户对象")
public class User {
    
    
    @ApiModelProperty(value = "用户ID", example = "1")
    private Long id;
    @ApiModelProperty(value = "用户名", required = true)
    private String username;
    @ApiModelProperty(value = "密码", required = true, example = "123456")
    private String password;
}

上面的代码中,我们使用了 @ApiModelProperty 注解来为 User 类中的 id、username、password 三个属性添加描述信息。

4.10 @ApiResponses

该注解用于指定多个响应状态码和响应消息,并为不同状态码指定不同的响应信息。

@ApiResponses(
        value = {
    
    
                @ApiResponse(code = 200, message = "请求成功"),
                @ApiResponse(code = 400, message = "请求参数错误"),
                @ApiResponse(code = 401, message = "未授权"),
                @ApiResponse(code = 403, message = "拒绝访问"),
                @ApiResponse(code = 404, message = "资源不存在")
        }
)
public void handleRequests() {
    
    
    // ...
}

上面的代码中,我们使用了 @ApiResponses 注解来描述请求返回的状态码,指定了状态码为 200、400、401、403 和 404,并对应给出了相应的提示信息。

4.11 @ApiParamImplicit@ApiParamImplicitSet

这两个注解用于为请求参数列表中的多个参数添加描述信息,在 Swagger 2.0 版本中已经被废弃,推荐使用 @ApiImplicitParams@ApiImplicitParam 注解代替。

@ApiParamImplicitSet({
    
    
        @ApiParamImplicit(name = "name", value = "用户名", required = true, dataType = "string", paramType = "query"),
        @ApiParamImplicit(name = "password", value = "密码", required = true, dataType = "string", paramType = "query")
})
public void login(String name, String password) {
    
    
    // ...
}

上面的代码中,我们使用了 @ApiParamImplicitSet 注解来为请求参数列表中的多个参数添加描述信息。

总结起来,Swagger 提供了众多注解和配置方式用于生成 API 文档,可根据具体情况灵活应用。:

  • @Api:描述整个 API 定义信息,并提供基本信息,例如版本、标题、描述、协议等。
  • @ApiOperation:描述 API 操作信息,例如描述、HTTP 方法、URL 等。
  • @ApiParam:描述参数信息,例如名称、数据类型、必填、描述信息等。
  • @ApiResponse:描述 API 响应信息,例如状态码、描述信息、响应模型等。
  • @ApiImplicitParam@ApiImplicitParams:描述请求参数信息,例如名称、数据类型、必填、描述信息等。
  • @RequestBody:描述请求体参数信息,例如名称、数据类型、必填、描述信息等。
  • @ApiIgnore:忽略指定项(类、方法、参数)的 API 文档生成,适用于那些不需要对外暴露的接口或属性。
  • @ApiModel:为数据模型添加描述信息,包括名称、描述、属性等。
  • @ApiModelProperty:为数据模型中的属性添加描述信息,包括名称、描述、数据类型、默认值等。
  • @ApiResponses:指定多个响应状态码和响应消息,并为不同状态码指定不同的响应信息。
  • @ApiParamImplicit@ApiParamImplicitSet:为请求参数列表中的多个参数添加描述信息,在 Swagger 2.0 版本中已经被废弃,推荐使用 @ApiImplicitParams@ApiImplicitParam 注解代替。

使用 Swagger 可以轻松地生成清晰明了的 API 文档,方便用户了解 API 的功能和使用方法。同时,我们也可以通过 Swagger 自动生成的文档检查 API 是否符合要求,提高开发效率和质量。

猜你喜欢

转载自blog.csdn.net/u012581020/article/details/130930253