Swagger 与 Spring Boot REST API 集成详解

Swagger是什么

Swagger(Swagger 2)是描述和记录REST API的一个规范。它指定了REST Web服务的格式,包括URL,资源,方法等。Swagger将从应用程序代码生成文档,并处理渲染部分。

在这篇文章中,我会将Swagger 2文档集成到基于Spring Boot的REST Web服务中。我将使用Springfox实现来生成swagger文档。如果你想知道是如何运行/构建Spring Boot项目的,请参考我上一篇文章。

Springfox提供了两个依赖关系来生成API文档和Swagger UI。如果你不希望将Swagger UI集成到你的API中,则无需添加Swagger UI依赖关系。

<dependency>

<groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency>
<dependency>

<groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>

EnableSwagger2注解启用了Springfox Swagger在类中的支持。为了记录这个服务,Springfox使用了一个Docket类。Docket有助于配置要记录的服务,并通过名称等进行分组。后台是Springfox通过使用基于Spring配置的API语义,在运行时检查应用程序。换句话说,你必须创建一个使用Spring的@Configuration注解的Spring Java Configuration类。

在我的例子中,我会生成一个基于我添加的RestController类的swagger文档。

import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class ApplicationConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.chandana.helloworld.controllers")) .paths(PathSelectors.any()) .build(); } }

由于我添加了两个控制器,因此将分别对每个控制器相关的API进行分组(标记)。

开箱即用,Springfox提供了5种断言,它们分别是any,none,withClassAnnotation,withMethodAnnotation和basePackage【译者注:参见springfox.documentation.builders. RequestHandlerSelectors类】

ApiInfo

Swagger提供了一些默认值,例如“API文档”,“通过联系人电子邮件创建”,“Apache 2.0”。当然你可以通过添加apiInfo(ApiInfo apiInfo)方法来更改这些默认值。ApiInfo类包含有关API的自定义信息。

@Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2) .apiInfo(getApiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.chandana.helloworld.controllers")) .paths(PathSelectors.any()) .build(); } private ApiInfo getApiInfo() { Contact contact = new Contact("Chandana Napagoda", "http://blog.napagoda.com", "[email protected]"); return new ApiInfoBuilder() .title("Example Api Title") .description("Example Api Definition") .version("1.0.0") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") .contact(contact) .build(); }

一旦添加了ApiInfo,生成的文档看起来就像这样:

Controller和POJO层文档

@Api注解用于说明每个控制器类(有点像类注释)。

@ApiOperation注解用于描述资源和方法。

@ApiResponse注解用于说明操作返回的其他响应值。例如:200 ok或202 accepted等

@ApiModelProperty注解用来描述POJO(Bean)类的属性(属性描述)。

添加上述注释后,最终生成的swagger文档如下所示:

Spring RestController类:

package com.chandana.helloworld.controllers;

import com.chandana.helloworld.bean.Greeting;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") @Api(value = "user", description = "Rest API for user operations", tags = "User API") public class HelloWorldController { @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "Display greeting message to non-admin user", response = Greeting.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "The resource not found") } ) public Greeting message(@PathVariable String name) { Greeting msg = new Greeting(name, "Hello " + name); return msg; } }

Greeting模型类:

package com.chandana.helloworld.bean;

import io.swagger.annotations.ApiModelProperty;

public class Greeting { @ApiModelProperty(notes = "Provided user name", required =true) private String player; @ApiModelProperty(notes = "The system generated greeting message" , readOnly =true) private String message; public Greeting(String player, String message) { this.player = player; this.message = message; } public String getPlayer() { return player; } public void setPlayer(String player) { this.player = player; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }

AppConfig类:

package com.chandana.helloworld.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class ApplicationConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(getApiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.chandana.helloworld.controllers")) .paths(PathSelectors.any()) .build(); } private ApiInfo getApiInfo() { Contact contact = new Contact("Chandana Napagoda", "http://blog.napagoda.com", "[email protected]"); return new ApiInfoBuilder() .title("Example Api Title") .description("Example Api Definition") .version("1.0.0") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") .contact(contact) .build(); } }

你也可以从我的GitHub repo 下载  Swagger Spring Boot Project 源代码。

译者注:

  1. 如果你对Spring Boot不是很熟悉,建议先fork下源码,因为有些依赖文中没有提到。
  2. 启动Spring Boot后,在浏览器中输入:127.0.0.1:8080/swagger-ui.html即可查看生成的文档信息。

在生成的文档页面中,可以输入参数,点击“Try it out!”即可进行接口测试,有点类似于Postman的功能。

猜你喜欢

转载自www.cnblogs.com/xiaobin123/p/12730262.html