Spring Boot中使用Swagger2构建强大的RESTful API文档

由于Spring Boot能够快速开发、便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API。而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端。

这样一来,我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发、Android开发或是Web开发等。为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTful API文档来记录所有接口细节,然而这样的做法有以下几个问题:

由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下游的抱怨声不绝于耳。
随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。

为了解决上面这样的问题,本文将介绍RESTful API的重磅好伙伴Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。具体效果如下图所示:
在这里插入图片描述
下面来具体介绍,如果在Spring Boot中使用Swagger2。

添加Swagger2依赖

在pom.xml中加入Swagger2的依赖

<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>

创建Swagger2配置类

在Application.java同级创建Swagger2的配置类Swagger2。

//swagger2的配置文件,在项目的启动类的同级文件建立
@Configuration
@EnableSwagger2
//是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable",  havingValue = "true")
public class Swagger2 {
    // swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.yh.common.config")).paths(PathSelectors.any())
                .build();
    }
    // 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title("Spring Boot 测试使用 Swagger2 构建RESTful API")
                // 创建人信息
                .contact(new Contact("cyh",  "https://www.cnblogs.com/zs-notes/category/1258467.html",  "1378975235@qq.com"))
                // 版本号
                .version("1.0")
                // 描述
                .description("API 描述")
                .build();
    }
}

如上代码所示,通过@Configuration 注解,让Spring来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2。如果这个位置不生效则在启动类加@Configuration。

再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
添加文档内容

在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。

@RestController
@RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下,可去除
public class UserController {

    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @ApiOperation(value="获取用户列表", notes="")
    @RequestMapping(value={""}, method=RequestMethod.GET)
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}

完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html
。就能看到前文所展示的RESTful API的页面。我们可以再点开具体的API请求,以POST类型的/users请求为例,可找到上述代码中我们配置的Notes信息以及参数user的描述信息,如下图所示。
在这里插入图片描述API文档访问与调试

在上图请求的页面中,我们看到user的Value是个输入框?是的,Swagger除了查看接口功能外,还提供了调试测试功能,我们可以点击上图中右侧的Model Schema(黄色区域:它指明了User的数据结构),此时Value中就有了user对象的模板,我们只需要稍适修改,点击下方“Try it out!”按钮,即可完成了一次请求调用!

此时,你也可以通过几个GET请求来验证之前的POST请求是否正确。

相比为这些接口编写文档的工作,我们增加的配置内容是非常少而且精简的,对于原有代码的侵入也在忍受范围之内。因此,在构建RESTful API的同时,加入swagger来对API文档进行管理,是个不错的选择。

Swagger2.X注解

常用到的注解有:
在这里插入图片描述
1. @Api标记
Api 用在类上,说明该类的作用。可以标记一个 Controller 类做为 swagger 文档资源,使用方式

@Api(value = "/user", description = "Operations about user")

与Controller注解并列使用。 属性配置:
在这里插入图片描述在SpringMvc中的配置如下:

@RestController
@RequestMapping(value = "/app/table")
@Api(value = "/app/table", protocols = "http")
public class AppTableController {

}

2. @ApiOperation标记
ApiOperation:用在方法上,说明方法的作用,每一个url资源的定义,使用方式:

@ApiOperation(
          value = "Find purchase order by ID",
          notes = "",
          response = A.class,
          tags = {""})

与Controller中的方法并列使用。
属性配置:
在这里插入图片描述在SpringMvc中的配置如下:

@ApiOperation(value = "/createCode", notes = "创建文件", response = ResultObj.class)
@RequestMapping(value = "/createCode")
public ResultObj createCode(
        @RequestParam(value = "tab_name", required = true) String tab_name
        , @RequestParam(value = "type", required = true) Integer type
        , @RequestParam(value = "includeSwagger", required = true) Boolean includeSwagger
        , @RequestParam(value = "moduleName", required = true) String moduleName
        , @RequestParam(value = "packageName", required = true) String packageName) {
    return ResultObj.getDefaultResponse(appTableService.listTable(tab_name, null));
}

3. @ApiImplicitParams、@ApiImplicitParam、@ApiParam标记

@ApiImplicitParams

只有value一个属性,用来装多个@ApiImplicitParam。

@ApiImplicitParam

用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

在这里插入图片描述
paramType:

header-->请求参数的获取:@RequestHeader(代码中接收注解)    
query-->请求参数的获取:@RequestParam(代码中接收注解)    
path(用于restful接口)-->请求参数的获取:@PathVariable(代码中接收注解) 
body-->请求参数的获取:@RequestBody(代码中接收注解)    
form(不常用))

使用方式

@ApiOperation(value = "/createCode", notes = "创建文件", response = ResultObj.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "表名", value = "tab_name", paramType = "query", dataType = "String", required = true)
, @ApiImplicitParam(name = "生成代码类别参数", value = "type", paramType = "query", dataType = "Integer", required = true)
})
@RequestMapping(value = "/createCode")
    public ResultObj createCode(
        @RequestParam(value = "tab_name", required = true) String tabName
        , @RequestParam(value = "type", required = true, defaultValue = "-1") Integer type){return null;}

@ApiParam

用在接收参数中,指定一个请求参数的信息

在这里插入图片描述具体参考文档v1.5.0

@ApiParam请求属性,使用方式:与Controller中的方法并列使用。

属性配置:
在这里插入图片描述在SpringMvc中的配置如下:

 public ResponseEntity<Order> getOrderById(
      @ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)
      @PathVariable("orderId") String orderId)

4. @ApiModel、@ApiModelProperty

@ApiModel

描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用 @ApiImplicitParam注解进行描述的时候;

在这里插入图片描述
@ApiModelProperty

描述一个model的属性。

@Table(name = "app_table", schema = "", catalog = "")
@ApiModel(value = "物理表信息表", description = "当前数据库表信息")
public class AppTable implements Serializable {

    private static final long serialVersionUID = -1L;

    @Id
    @Column(name = "tab_name", unique = true)
    @ApiModelProperty(value = "表名主键")

5. @ApiResponses、@ApiResponse

@ApiResponses:响应集配置,使用方式:

 @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })

与Controller中的方法并列使用。 属性配置:

在这里插入图片描述
在SpringMvc中的配置如下:

 @RequestMapping(value = "/order", method = POST)
  @ApiOperation(value = "Place an order for a pet", response = Order.class)
  @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
  public ResponseEntity<String> placeOrder(
      @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
    storeData.add(order);
    return ok("");
  }

@ApiResponse:响应配置,使用方式:

@ApiResponse(code = 400, message = "Invalid user supplied")

与Controller中的方法并列使用。 属性配置:
在这里插入图片描述在SpringMvc中的配置如下:

 @RequestMapping(value = "/order", method = POST)
  @ApiOperation(value = "Place an order for a pet", response = Order.class)
  @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
  public ResponseEntity<String> placeOrder(
      @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
    storeData.add(order);
    return ok("");
  }

6. ResponseHeader

响应头设置,使用方法

@ResponseHeader(name="head1",description="response head conf")

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java技术实践

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值