网站建设盐城最便宜,张雪峰谈工业设计专业,如何做一个单页面的网站,做视频网站版权怎么解决第6章 构建 RESTful 服务 6.1 RESTful 简介 6.2 构建 RESTful 应用接口 6.3 使用 Swagger 生成 Web API 文档 6.4 实战#xff1a;实现 Web API 版本控制 6.3 使用 Swagger 生成 Web API 文档
高质量的 API 文档在系统开发的过程中非常重要。本节介绍什么是 Swagger#xff… 第6章 构建 RESTful 服务 6.1 RESTful 简介 6.2 构建 RESTful 应用接口 6.3 使用 Swagger 生成 Web API 文档 6.4 实战实现 Web API 版本控制 6.3 使用 Swagger 生成 Web API 文档
高质量的 API 文档在系统开发的过程中非常重要。本节介绍什么是 Swagger 如何在 Spring Boot 项目中集成 Swagger 构建 RESTful API 文档以及为 Swagger 配置 Token 等通用参数。
6.3.1 什么是 Swagger Swagger 是一个规范和完整的框架用于生成、描述、调用和可视化 RESTful 风格的 Web 服务是非常流行的 API 表达工具。 普通的API文档存在的问题
由于接口众多并且细节复杂需要考虑不同的 HTTP 请求类型、HTTP 头部信息、HTTP 请求内容等创建这样一份高质量的文档是一件非常繁琐的工作。随着需求的不断变化接口文档必须同步修改就很容易出现文档和业务不一致的情况。
为了解决这些问题Swagger 应运而生它能够自动生成完善的 RESTful API 文档并根据后台代码的修改同步更新。这样既可以减少维护接口文档的工作量又能将说明内容集成到实现代码中让维护文档和修改代码合为一体实现代码逻辑与说明文档的同步更新。另外Swagger 也提供了完整的测试页面来测试 API让 API 测试变得轻松、简单。
6.3.2 使用 Swagger 生成 Web API 文档
1、配置 Swagger 的依赖。
在pom.xml 文件中引入 Swagger 相关依赖包springfox-swagger2、springfox-swagger-ui。如下
pom.xml !--Swagger2 依赖配置--dependencygroupIdio.springfox/groupIdartifactIdspringfox-swagger2/artifactIdversion2.8.0/version/dependencydependencygroupIdio.springfox/groupIdartifactIdspringfox-swagger-ui/artifactIdversion2.5.0/version/dependency2、创建 Swagger2 配置类。
Swagger2Config.java
package com.example.restfulproject.comm.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;/*** Swagger2 配置类*/
Configuration
EnableSwagger2
public class Swagger2Config implements WebMvcConfigurer {Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage(com.example.restfulproject)).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title(Spring Boot 中使用 Swagger2 构建 RESTful APIs).description(Spring Boot 相关文章请关注https://blog.csdn.net/shipley_leo).termsOfServiceUrl(https://blog.csdn.net/shipley_leo).contact(shipley_leo).version(1.0).build();}Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler(swagger-ui.html).addResourceLocations(classpath:/META-INF/resources/);registry.addResourceHandler(/webjars/**).addResourceLocations(classpath:/META-INF/resources/webjars/);}
}在上面的示例中我们在 SwaggerConfig 的类上添加了Configuration和EnableSwagger2两个注解。
Configuration 注解让 Spring Boot 来加载该类配置。EnableSwagger2 注解启用 Swagger2通过配置一个 Docket Bean来配置映射路径和要扫描的接口所在的位置。apiInfo() 方法主要配置 Swagger2 文档网站的信息比如网站的标题、网站的描述、使用的协议等。
3、添加文档说明内容。
SwaggerController.java
package com.example.restfulproject.controller;import com.example.restfulproject.comm.utils.JSONResult;
import com.example.restfulproject.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;/*** 使用 Swagger 生成 Web API 文档*/
Api(tags {用户接口})
RestController
RequestMapping(value /swagger)
public class SwaggerController {ApiOperation(value 创建用户, notes 根据 User 对象创建用户)PostMapping(value /user)public JSONResult save(RequestBody User user) {System.out.println(用户创建成功 user.getName());return JSONResult.ok(201, 用户创建成功);}ApiOperation(value 更新用户详细信息, notes 根据 id 来指定更新对象并根据传过来的 user 信息来更新用户详细信息)PutMapping(value /user)public JSONResult update(RequestBody User user) {System.out.println(用户修改成功 user.getName());return JSONResult.ok(203, 用户修改成功);}ApiOperation(value 删除用户, notes 根据 url 的 id 来指定删除对象)ApiImplicitParam(name userId, value 用户ID, required true, dataType String, paramType path)DeleteMapping(value /user/{userId})public JSONResult delete(PathVariable String userId) {System.out.println(用户删除成功 userId);return JSONResult.ok(204, 用户删除成功);}ApiOperation(value 查询用户, notes 通过用户 ID 获取用户信息)ApiImplicitParam(name userId, value 用户ID, required true, dataType String, paramType path)GetMapping(value /user/{userId})public JSONResult queryUserById(PathVariable String userId) {User user new User();user.setId(userId);user.setName(zhangsan);user.setAge(20);System.out.println(获取用户成功 userId);return JSONResult.ok(200, 获取用户成功, user);}}
在上面的示例中主要为 SwaggerController 中的接口增加了接口信息描述包括接口的用途请求参数说明等。
Api 注解用来给整个控制器Controller增加说明。ApiOperation 注解用来给各个 API 方法增加说明。ApiImplicitParams、ApiImplicitParam 注解用来给参数增加说明。
4、查看生成的 API 文档。
1查看生成的 API 文档
完成上面的配置和代码修改之后Swagger2 就集成到 Spring Boot 项目中了。接下来启动项目在浏览器中访问 http://localhost:8080/swagger-ui.html Swagger 会自动构建接口说明文档如图所示。 swagger-ui.htmlSwagger-UI 启动页面 用户接口 创建用户 更新用户详细信息 删除用户 查询用户 Swagger 自动将用户管理模块的全部接口信息展现出来包括接口功能说明、调用方式、请求参数、返回数据结构等信息。
2Swagger 接口验证测试
在 Swagger 页面上我们发现每个接口描述左下方都有一个按钮“Try it out!”点击该按钮即可调用该接口进行测试。如图所示输入userId请求参数“1001”然后单击“Try it out!”按钮就会将请求发送到后台从而进行接口验证测试。 调用接口进行测试 答疑解惑 报错问题Spring Boot 整合 Swagger 用于生成 Web API 文档的过程中出现了一个报错“Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException”。 原因分析这个报错是因为 springboot 升级到 2.6.0之后swagger版本和springboot出现了不兼容情况。 解决方案有三种解决方案可供参考使用分别为 方案一在启动类 或 配置类 添加注解 EnableWebMvc。方案二在 application.properties 配置文件添加配置 properties spring.mvc.pathmatch.matching-strategyant_path_matcher方案三降低Spring Boot 版本比如可以考虑将Spring Boot版本降低为2.5.6。 更加详细的说明可参考Failed to start bean ‘documentationPluginsBootstrapper‘ nested exception is java.lang.NullPointerEx 6.3.3 为 Swagger 添加 token 参数
很多时候客户端在调用 API 时需要在 HTTP 的请求头携带通用参数比如权限验证的 token 参数等。但是 Swagger 是怎么描述此类参数的呢接下来通过示例演示如何为 Swagger 添加固定的请求参数。
其实非常简单修改 Swagger2Config 配置类利用 ParameterBuilder 构成请求参数具体示例代码如下
package com.example.restfulproject.comm.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.ArrayList;
import java.util.List;/*** Swagger2 配置类*/
Configuration
EnableSwagger2
public class Swagger2Config implements WebMvcConfigurer {Beanpublic Docket createRestApi() {ListParameter parameters new ArrayListParameter();ParameterBuilder parameterBuilder new ParameterBuilder();parameterBuilder.name(token).description(token令牌).modelRef(new ModelRef(string)).parameterType(header).required(false).build();parameters.add(parameterBuilder.build());return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage(com.example.restfulproject.controller)).paths(PathSelectors.any()).build().globalOperationParameters(parameters);}...
}
在上面的示例中通过 ParameterBuilder 类把 token 作为全局统一的参数添加到 HTTP 的请求头中。系统所有的 API 都会统一加上此参数。
完成之后重新启动应用再次查看接口如图所示我们可以看到接口参数中已经支持发送 token 请求参数。 6.3.4 Swagger 常用注解
Swagger 提供了一系列注解来描述接口信息包括接口说明、请求方法、请求参数、返回信息等常用注解如表所示。
Swagger常用注解说明
注解属性取值类型说明示例Apivalue字符串可用在class头上class描述Api(valuexxx, descriptionxxx)description字符串ApiOperationvalue字符串可用在方法头上参数的描述容器ApiOperation(valuexxx,notesxxx)notes字符串ApiImplicitParamsvalueApiImplicitParam数组可用在方法头上参数的描述容器ApiImplicitParams({ApiImplicitParam1,ApiImplicitParam2...})ApiImplicitParamname字符串与参数命名对应可用在ApiImplicitParams中ApiImplicitParam(name userId, value 用户ID, required true, dataType String, paramType path)value字符串参数中文描述required布尔值true/falsedataType字符串参数类型paramType字符串参数请求方式query/pathdefaultValue字符串在API测试中的默认值ApiResponsesvalueApiResponse数组可用在方法头上参数的描述容器ApiResponses({ApiResponse1,ApiResponse2,...})ApiResponsecode整数可用在ApiResponses中ApiResponse(code200, messageSuccessful)message字符串错误描述ApiIgnorevalue字符串忽略这个APIApiError发生错误的返回信息
在实际项目中Swagger 除了提供 ApiImplicitParams 注解描述简单的参数之外还提供了用于对象参数的 ApiModel 和 ApiModelProperty 两个注解用于封装的对象作为传入参数或返回数据。
ApiModel 负责描述对象的信息ApiModelProperty 负责描述对象中属性的相关内容
以上是在项目中常用的一些注解利用这些注解就可以构建出清晰的 API 文档。 来源《Spring Boot 从入门到实战》学习笔记