一、为什么要用Swagger?
前后端分离
- 前端 -> 前端控制层、视图层
- 后端 -> 后端控制层、服务层、数据访问层
- 前后端通过API进行交互
- 前后端相对独立且松耦合
产生的问题
- 前后端集成,前端或者后端无法做到“及时协商,尽早解决”,最终导致问题集中爆发
解决方案
- 首先定义schema ,并实时跟踪最新的API,降低集成风险
二、什么是Swagger?
Restful Api 文档在线自动生成器 → API 文档 与API 定义同步更新 ( 可以直接运行,在线测试API )
Swagger官网: https://swagger.io/
三、如何使用Swagger?(最简单详细创建步骤)
以SpringBoot框架+Swagger组件为例(JDK1.8及以上):
-
Step1:新建一个SpringBoot工程。
-
Step2:添加Swagger依赖包。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.2.6.RELEASE</version> </dependency> <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>
-
Step3:添加启动类。
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @description: 启动类 * @author: Create by Liu Wen at 2020-06-13 15:12 **/ @SpringBootApplication public class SwaggerApplication { public static void main(String[] args){ SpringApplication.run(SwaggerApplication.class,args); } }
-
Step4:添加Swagger配置(这是最小配置)。
package com.example.demo.config; import org.springframework.context.annotation.Configuration; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @description: Swagger配置 * 启动后默认访问:http://localhost:8080/swagger-ui.html * @author: Create by Liu Wen at 2020-06-13 15:11 **/ @Configuration //配置类 @EnableSwagger2 //开启Swagger2自动配置 public class SwaggerConfig { }
-
Step5:添加控制层Controller,用于测试。访问链接:http://localhost:8080/swagger-ui.html 可以看到 swagger的界面;
package com.example.demo.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @description: 测试API接口层(即控制层) * @author: Create by Liu Wen at 2020-06-13 15:12 **/ @RestController @RequestMapping("/swagger") public class SwaggerController { }
-
Swagger界面如下:
四、Swagger进阶配置
-
Step4:添加Swagger配置(完整配置)
Swagger注解 简单说明 @Api(tags = “xxx模块说明”) 作用在模块类上 @ApiOperation(“xxx接口说明”) 作用在接口方法上 @ApiModel(“xxxPOJO说明”) 作用在模型类上:如VO、BO @ApiModelProperty(value = “xxx属性说明”,hidden = true) 作用在类方法和属性上,hidden设置为true可以隐藏该属性 @ApiParam(“xxx参数说明”) 作用在参数、方法和字段上,类似@ApiModelProperty
package com.example.demo.config;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;
/**
* @description: Swagger配置
* 默认访问:http://localhost:8080/swagger-ui.html
* @author: Create by Liu Wen at 2020-06-13 15:11
**/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger。
* 如何配置多个分组?配置多个分组只需要配置多个Docket即可:
*/
@Bean
public Docket restfulApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("RestfulApi")
.genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
// base,最终调用接口后会和paths拼接在一起
.select()
.paths(doFilteringRules())
.build()
.apiInfo(initApiInfo());
}
private ApiInfo initApiInfo() {
ApiInfo apiInfo = new ApiInfo("XXX项目 Platform API",//大标题
initContextInfo(),//简单的描述
"1.0.0",//版本
"服务条款",
"后台开发团队",//作者
"The Apache License, Version 2.0",//链接显示文字
"http://www.baidu.com"//网站链接
);
return apiInfo;
}
private String initContextInfo() {
StringBuffer sb = new StringBuffer();
sb.append("REST API 设计在细节上有很多自己独特的需要注意的技巧,并且对开发人员在构架设计能力上比传统 API 有着更高的要求。")
.append("<br/>")
.append("本文通过翔实的叙述和一系列的范例,从整体结构,到局部细节,分析和解读了为了提高易用性和高效性,REST API 设计应该注意哪些问题以及如何解决这些问题。");
return sb.toString();
}
/**
* 设置过滤规则,这里的过滤规则支持正则匹配
*/
private Predicate<String> doFilteringRules() {
return or(
regex("/hello.*"),
regex("/vehicles.*")
);
}
}
- Step5:添加控制层Controller,用于测试。
package com.example.demo.controller;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.swing.text.ChangedCharSetException;
import java.util.Date;
/**
* @description: 测试API接口层(即控制层)
* @author: Create by Liu Wen at 2020-06-13 15:12
**/
@Api(value = "API - VehiclesController", description = "车辆模块接口详情")
@RestController
@RequestMapping("/vehicles")
public class SwaggerController {
private static Logger logger = LoggerFactory.getLogger(SwaggerController.class);
@ApiOperation(value = "查询车辆接口", notes = "此接口描述xxxxxxxxxxxxx<br/>xxxxxxx<br>值得庆幸的是这儿支持html标签<hr/>", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "vno", value = "车牌", required = false,
dataType = "string", paramType = "query", defaultValue = "辽A12345"),
@ApiImplicitParam(name = "page", value = "page", required = false,
dataType = "Integer", paramType = "query", defaultValue = "1"),
@ApiImplicitParam(name = "count", value = "count", required = false,
dataType = "Integer", paramType = "query", defaultValue = "10")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful — 请求已完成"),
@ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
@ApiResponse(code = 401, message = "未授权客户机访问数据"),
@ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
@ApiResponse(code = 500, message = "服务器不能完成请求")}
)
@ResponseBody
@RequestMapping(value = "", method = RequestMethod.GET)
public ModelMap findVehicles(@RequestParam(value = "vno", required = false) String vno,
@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "count", required = false) Integer count)
throws Exception {
logger.info("http://localhost:8501/api/v1/vehicles");
logger.info("## {},{},{}", vno, page, count);
logger.info("## 请求时间:{}", new Date());
ModelMap map = new ModelMap();
map.addAttribute("vno", vno);
map.addAttribute("page", page);
return map;
}
@ApiOperation(value = "根据车牌查询车辆", notes = "这种类型的查询是精确查询,其结果只有一条数据", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "vno", value = "车牌", required = false,
dataType = "string", paramType = "path", defaultValue = "辽A12345")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful — 请求已完成"),
@ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
@ApiResponse(code = 401, message = "未授权客户机访问数据"),
@ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
@ApiResponse(code = 500, message = "服务器不能完成请求")}
)
@ResponseBody
@RequestMapping(value = "vno={vno}", method = RequestMethod.GET)
public ModelMap getVno(@PathVariable(value = "vno") String vno)
throws Exception {
logger.info("http://localhost:8501/api/v1/vehicles/vno={}", vno);
logger.info("## 请求时间:{}", new Date());
ModelMap map = new ModelMap();
map.addAttribute("vno", vno);
return map;
}
@ApiOperation(value = "车辆位置查询接口", notes = "根据车牌查询车辆位置信息", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "vno", value = "车牌", required = false,
dataType = "string", paramType = "path", defaultValue = "辽A12345")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful — 请求已完成"),
@ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
@ApiResponse(code = 401, message = "未授权客户机访问数据"),
@ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
@ApiResponse(code = 500, message = "服务器不能完成请求")}
)
@ResponseBody
@RequestMapping(value = "vno={vno}/location", method = RequestMethod.GET)
public ModelMap getLocation(@PathVariable(value = "vno") String vno)
throws Exception {
logger.info("getLocation");
logger.info("## 请求时间:{}", new Date());
ModelMap map = new ModelMap();
map.addAttribute("vno", vno);
return map;
}
@ApiOperation(value = "根据车辆id查询", notes = "精确查询,最常规的方式,支持POST和GET方式", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "id", required = false,
dataType = "string", paramType = "path", defaultValue = "12344444")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful — 请求已完成"),
@ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
@ApiResponse(code = 401, message = "未授权客户机访问数据"),
@ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
@ApiResponse(code = 500, message = "服务器不能完成请求")}
)
@ResponseBody
@RequestMapping(value = "{id}", method = {RequestMethod.GET, RequestMethod.POST})
public ModelMap getById(@PathVariable(value = "id") String id)
throws Exception {
logger.info("http://localhost:8501/api/v1/vehicles/{}", id);
logger.info("## 请求时间:{}", new Date());
ModelMap map = new ModelMap();
map.addAttribute("{RequestMethod.GET,RequestMethod.POST}", id);
return map;
}
@ApiOperation(value = "根据车辆id查询", notes = "精确查询,最常规的方式,支持POST和GET方式", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "id", required = false,
dataType = "string", paramType = "path", defaultValue = "12344444")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful — 请求已完成"),
@ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
@ApiResponse(code = 403, message = "服务器拒绝请求"),
@ApiResponse(code = 401, message = "未授权客户机访问数据"),
@ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
@ApiResponse(code = 500, message = "服务器不能完成请求")}
)
@ResponseBody
@RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
public ModelMap delById(@PathVariable(value = "id") String id)
throws Exception {
logger.info("http://localhost:8501/api/v1/vehicles/{}", id);
logger.info("## 请求时间:{}", new Date());
ModelMap map = new ModelMap();
map.addAttribute("RequestMethod.DELETE", id);
return map;
}
@ApiOperation(value = "网点挂靠", notes = "嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻", response = String.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful — 请求已完成"),
@ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
@ApiResponse(code = 401, message = "未授权客户机访问数据"),
@ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
@ApiResponse(code = 500, message = "服务器不能完成请求")}
)
@ResponseBody
@RequestMapping(value = "change_rentalshop", method = {RequestMethod.PUT, RequestMethod.PATCH})
public ModelMap changeRentalShop(@RequestBody ChangedCharSetException parameter)
throws Exception {
logger.info("http://localhost:8501/api/v1/vehicles/change_rentalshop | {}", parameter);
logger.info("## 请求时间:{}", new Date());
ModelMap map = new ModelMap();
map.addAttribute("网点挂靠", new Date());
return map;
}
}
- 最终的Swagger界面如下:
五、总结
相较于传统的Postman或Curl方式测试接口,使用swagger简直就是傻瓜式操作,不需要额外说明文档(写得好本身就是文档)而且更不容易出错,只需要录入数据然后点击Execute,如果再配合自动化框架,可以说基本就不需要人为操作了。
Swagger是个优秀的工具,现在国内已经有很多的中小型互联网公司都在使用它,相较于传统的要先出Word接口文档再测试的方式,显然这样也更符合现在的快速迭代开发行情。当然了,提醒下大家在正式环境要记得关闭Swagger,一来出于安全考虑二来也可以节省运行时内存。