更多内容,前往 IT-BLOG

如今,REST和微服务已经有了很大的发展势头。但是,REST规范中并没有提供一种规范来编写我们的对外 REST接口 API文档。每个人都在用自己的方式记录 api文档,因此没有一种标准规范能够让我们很容易的理解和使用该接口。我们需要一个共同的规范和统一的工具来解决文档的难易理解文档的混乱格式。Swagger(在谷歌、IBM、微软等公司的支持下)做了一个公共的文档风格来填补上述问题。在本博客中,我们将会学习怎么使用 Swagger的 Swagger2注解去生成REST API文档。

Swagger(现在是“开放 API计划”)是一种规范和框架,它使用一种人人都能理解的通用语言来描述 REST API。还有其他一些可用的框架,比如 RAML、求和等等,但是 Swagger是最受欢迎的。它提供了人类可读和机器可读的文档格式。它提供了 JSON UI支持。JSON可以用作机器可读的格式,而 Swagger-UI是用于可视化的,通过浏览 api文档,人们很容易理解它。

一、添加 Swagger2 的 maven依赖


打开项目中的 pom.xml文件,添加以下两个 swagger依赖。springfox-swagger2 、springfox-swagger-ui。

 1 <dependency>
2 <groupId>io.springfox</groupId>
3 <artifactId>springfox-swagger2</artifactId>
4 <version>2.6.1</version>
5 </dependency>
6
7 <dependency>
8 <groupId>io.springfox</groupId>
9 <artifactId>springfox-swagger-ui</artifactId>
10 <version>2.6.1</version>
11 </dependency>

实际上,Swagger的 API有两种类型,并在不同的工件中维护。今天我们将使用 springfox,因为这个版本可以很好地适应任何基于 spring的配置。我们还可以很容易地尝试其他配置,这应该提供相同的功能——配置中没有任何变化。

二、添加 Swagger2配置


使用 Java config的方式添加配置。为了帮助你理解这个配置,我在代码中写了相关的注释:

 1 import org.springframework.context.annotation.Bean;
2 import org.springframework.context.annotation.Configuration;
3 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
4 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
5 import com.google.common.base.Predicates;
6 import springfox.documentation.builders.RequestHandlerSelectors;
7 import springfox.documentation.spi.DocumentationType;
8 import springfox.documentation.spring.web.plugins.Docket;
9 import springfox.documentation.swagger2.annotations.EnableSwagger2;
10
11 @Configuration
12 @EnableSwagger2
13 public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter
14 {
15 @Bean
16 public Docket api() {
17 // @formatter:off
18 //将控制器注册到 swagger
19 //还配置了Swagger 容器
20 return new Docket(DocumentationType.SWAGGER_2).select()
21 .apiInfo(apiInfo())
22 .select()
23 .apis(RequestHandlerSelectors.any())
24 //扫描 controller所有包
25 .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
26 .paths(PathSelectors.any())
27 .paths(PathSelectors.ant("/swagger2-demo"))
28 .build();
29 // @formatter:on
30 }
31
32 @Override
33 public void addResourceHandlers(ResourceHandlerRegistry registry)
34 {
35 //为可视化文档启用swagger ui部件
36 registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
37 registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
38 }
39 }

通过 api()方法返回 Docket,调用以下方法:
【1】apiInfo()方法中可以添加 api文档的基本信息(具体类型查看文档);
【2】select()方法返回 ApiSelectorBuilder实例,用于过滤哪些 api需要显示;
【3】apis()方法中填写项目中 Controller类存放的路径;
最后 build()建立 Docket。

三、验证 Swagger2的 JSON格式文档


在application.yml中配置服务名为:swagger2-demo

server.contextPath=/swagger2-demo

maven构建并启动服务器。打开链接 http://localhost:8080/swagger2-demo/v2/api-docs,会生成一个 JSON格式的文档。这并不是那么容易理解,实际上 Swagger已经提供该文档在其他第三方工具中使用,例如当今流行的 API管理工具,它提供了API网关、API缓存、API文档等功能。

四、验证 Swagger2 UI文档


打开链接 http://localhost:8080/swagger2-demo/swagger-ui.html 在浏览器中来查看 Swagger UI文档;

五、Swagger2 注解的使用


默认生成的 API文档很好,但是它们缺乏详细的 API级别信息。Swagger提供了一些注释,可以将这些详细信息添加到 api中。如。@Api 我们可以添加这个注解在 Controller上,去添加一个基本的 Controller说明。

1 @Api(value = "Swagger2DemoRestController", description = "REST APIs related to Student Entity!!!!")
2 @RestController
3 public class Swagger2DemoRestController {
4 //...
5 }

@ApiOperation and @ApiResponses我们添加这个注解到任何 Controller的 rest方法上来给方法添加基本的描述。例如:

 1 @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")
2 @ApiResponses(value = {
3 @ApiResponse(code = 200, message = "Success|OK"),
4 @ApiResponse(code = 401, message = "not authorized!"),
5 @ApiResponse(code = 403, message = "forbidden!!!"),
6 @ApiResponse(code = 404, message = "not found!!!") })
7
8 @RequestMapping(value = "/getStudents")
9 public List<Student> getStudents() {
10 return students;
11 }

在这里,我们可以向方法中添加标签,来在 swagger-ui中添加一些分组。@ApiModelProperty这个注解用来在数据模型对象中的属性上添加一些描述,会在 Swagger UI中展示模型的属性。例如:

1 @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
2 private String name;

Controller 和 Model 类添加了swagger2注解之后,代码清单:Swagger2DemoRestController.java

 1 import java.util.ArrayList;
2 import java.util.List;
3 import java.util.stream.Collectors;
4 import org.springframework.web.bind.annotation.PathVariable;
5 import org.springframework.web.bind.annotation.RequestMapping;
6 import org.springframework.web.bind.annotation.RestController;
7 import com.example.springbootswagger2.model.Student;
8 import io.swagger.annotations.Api;
9 import io.swagger.annotations.ApiOperation;
10 import io.swagger.annotations.ApiResponse;
11 import io.swagger.annotations.ApiResponses;
12
13 @Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!")
14 @RestController
15 public class Swagger2DemoRestController {
16
17 List<Student> students = new ArrayList<Student>();
18 {
19 students.add(new Student("Sajal", "IV", "India"));
20 students.add(new Student("Lokesh", "V", "India"));
21 students.add(new Student("Kajal", "III", "USA"));
22 students.add(new Student("Sukesh", "VI", "USA"));
23 }
24
25 @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")
26 @ApiResponses(value = {
27 @ApiResponse(code = 200, message = "Suceess|OK"),
28 @ApiResponse(code = 401, message = "not authorized!"),
29 @ApiResponse(code = 403, message = "forbidden!!!"),
30 @ApiResponse(code = 404, message = "not found!!!") })
31
32 @RequestMapping(value = "/getStudents")
33 public List<Student> getStudents() {
34 return students;
35 }
36
37 @ApiOperation(value = "Get specific Student in the System ", response = Student.class, tags = "getStudent")
38 @RequestMapping(value = "/getStudent/{name}")
39 public Student getStudent(@PathVariable(value = "name") String name) {
40 return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0);
41 }
42
43 @ApiOperation(value = "Get specific Student By Country in the System ", response = Student.class, tags = "getStudentByCountry")
44 @RequestMapping(value = "/getStudentByCountry/{country}")
45 public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
46 System.out.println("Searching Student in country : " + country);
47 List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
48 .collect(Collectors.toList());
49 System.out.println(studentsByCountry);
50 return studentsByCountry;
51 }
52
53 // @ApiOperation(value = "Get specific Student By Class in the System ",response = Student.class,tags="getStudentByClass")
54 @RequestMapping(value = "/getStudentByClass/{cls}")
55 public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
56 return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
57 }
58 }

Student.java 实体类

 1 import io.swagger.annotations.ApiModelProperty;
2
3 public class Student
4 {
5 @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
6 private String name;
7
8 @ApiModelProperty(notes = "Class of the Student",name="cls",required=true,value="test class")
9 private String cls;
10
11 @ApiModelProperty(notes = "Country of the Student",name="country",required=true,value="test country")
12 private String country;
13
14 public Student(String name, String cls, String country) {
15 super();
16 this.name = name;
17 this.cls = cls;
18 this.country = country;
19 }
20
21 public String getName() {
22 return name;
23 }
24
25 public String getCls() {
26 return cls;
27 }
28
29 public String getCountry() {
30 return country;
31 }
32
33 @Override
34 public String toString() {
35 return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]";
36 }
37 }

六、swagger-ui 展示


现在,当我们的 REST api得到适当的注释时,让我们看看最终的输出。打开http://localhost:8080/swagger2-demo/swagger-ui。在浏览器中查看 Swagger ui 文档。
​​

SpringBoot——Swagger2 接口规范的更多相关文章

  1. springboot+swagger2

    springboot+swagger2 小序 新公司的第二个项目,是一个配置管理终端机(比如:自动售卖机,银行取款机)的web项目,之前写过一个分模块的springboot框架,就在那个框架基础上进行 ...

  2. SpringBoot+Swagger2 整合

    SpringBoot+Swagger2四步整合 第一步:添加相关依赖 <parent> <groupId>org.springframework.boot</groupI ...

  3. Springboot+swagger2.7集成开发

    Springboot+swagger2.7集成开发 本篇文章是介绍最新的springboot和swagger2.7集成开发和2.0稍微有一些出入: Springboot集成环境配置 Swagger2. ...

  4. MP实战系列(八)之SpringBoot+Swagger2

    SpringBoot一个原则,爱好编程的朋友们都知道,那就是"习惯优于配置". 今天一上来主要说的还是代码,个人比较喜欢来的实战系列的,不过有的时候还是比较偏重于理论,理论是造轮子 ...

  5. springboot+swagger2案例

    1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www ...

  6. Springboot+swagger2的接口文档开发

    一.创建一个SpringBoot项目 1. 2. 3. 4. 把web里的web选中,SQL里选择自己需要的,点击next 二.创建各项所需的controller,configure等 1. 项目布局 ...

  7. SpringBoot + Swagger2 自动生成API接口文档

    spring-boot作为当前最为流行的Java web开发脚手架,相信越来越多的开发者会使用其来构建企业级的RESTFul API接口.这些接口不但会服务于传统的web端(b/s),也会服务于移动端 ...

  8. Springboot swagger2 导出api文档

    具体导出的代码,参考了:http://www.spring4all.com/article/699 导出前,首先需要配置好swagger2,参见 https://www.cnblogs.com/yan ...

  9. springboot + swagger2 生成api文档

    直接贴代码: <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-sw ...

  10. springboot + swagger2 学习笔记

    引入步骤 1.添加依赖 <dependency> <groupId>io.springfox</groupId> <artifactId>springf ...

随机推荐

  1. 学习dash篇-layout页面布局

    Dash介绍 Dash官网教程地址:https://dash.plotly.com/introduction 数据分析工作的结果,通常是数据表格.图表,分析报告.这些东西office的三件套基本都能满 ...

  2. Spring入门之使用 spring 的 IOC 解决程序耦合(Spring环境搭建)(03-01)

    3.1 案例的前期准备 1.使用的案例是:账户的业务层和持久层的依赖关系解决(就是有两个账户实现转账之类的事情,后期继续用这个案例)2.准备环境:在开始 spring 的配置之前,我们要先准备一下环境 ...

  3. idea中的快捷键

  4. 常用的DOS指令及部分快捷键

    常用的DOS指令及部分快捷键 1.dos打开方式 ​ win + R打开运行,输入cmd,打开dos 2.常用的Dos指令 a.切换盘号 方法 ​ 直接输入对应盘加" :" D: ...

  5. rabbitMq安装 - docker

    安装rabbitmq 参考网站:https://www.rabbitmq.com/download.html 方式一: 获取rabbit镜像: docker pull rabbitmq:managem ...

  6. react+antd pro实现【列表可实时行内编辑】的弹窗表单组件

    纯列表版效果展示: ① 初始无值,展示为唤醒按钮+文案外链 ②点击按钮唤醒弹窗(简易版示意图) ③配置后 可编辑表格组件文档: https://procomponents.ant.design/com ...

  7. Jmeter、Postman之RSA加密登录接口测试

    方法1:直接用在线加密工具进行加密,得到密码 参考地址 https://www.toolscat.com/decode/rsa 输入公钥和密码,直接加密即可   方法2:postman工具 步骤1:接 ...

  8. 4组-Beta冲刺-2/5

    一.基本情况 队名:摸鲨鱼小队 组长博客:https://www.cnblogs.com/smallgrape/p/15595704.html github链接:https://github.com/ ...

  9. Restful Fast Request 添加前置脚本,实现不同环境免设置token 直接请求

    idea安装Restful Fast Request插件后,进行如下设置,并打开 项目全局参数 对话框 进入前置脚本 tab 编写如下groovy脚本代码(插件脚本语言默认支持groovy,该语言被称 ...

  10. ubuntu16.04openssh升级

    wget http://zlib.net/zlib-1.2.11.tar.gz tar xf zlib-1.2.11.tar.gz && cd zlib-1.2.11/ ./confi ...