利用 Swagger 构建 Api 文档,提高你的对接效率

前言

Swagger 是一套基于 OpenAPI 规范构建的开源工具,能够帮助咱们设计、构建、记录以及使用 Rest API。愈来愈多的公司在项目中使用Swagger做为文档构建工具,Swagger主要有一下优势:html

  • 代码变,文档变。只须要少许的注解,Swagger 就能够根据代码自动生成 API 文档,很好的保证了文档的时效性
  • 跨语言性,支持 40 多种语言
  • Swagger UI 呈现出来的是一份可交互式的 API 文档,咱们能够直接在文档页面尝试 API 的调用,省去了准备复杂的调用参数的过程
  • 还能够将文档规范导入相关的工具(例如 SoapUI), 这些工具将会为咱们自动地建立自动化测试

若是你还在手写Api文档,你能够尝试使用swagger去构建你的文档。你是否已经对 Swagger 产生了浓厚的兴趣了呢?下面咱们就将一步一步地在 Spring Boot 项目中集成和使用 Swagger,让咱们从准备一个 Spring Boot 的 Web 项目开始吧。java

springboot 结合 swagger

一、在pom.xml中配置依赖

<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>
复制代码

二、配置swaggerconfig信息

咱们要使用swagger就须要编写一个swagger的配置文件,主要用来用来初始化swagger。配置信息以下:git

@EnableSwagger2
@Configuration
//@Profile({"dev","test"})
@ConditionalOnProperty(name = "swagger.enable",havingValue = "true")
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 扫描的包
                .apis(RequestHandlerSelectors.basePackage("com.curry.springbootswagger.controller"))
                // 选择API路径
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // swagger ui 的标题
                .title("Spring Boot中使用 Swagger2 构建 Restful APIs")
                // 描述
                .description("更多信息关注公众号 平头哥的技术博文")
                // 外链
                .termsOfServiceUrl("https://www.jianshu.com/u/008ce054774c")
                // 文档的版本信息
                .version("1.0")
                .build();
    }
}
复制代码

配置类的几个注解说明:程序员

@Configuration:将该类自动加载到springboot的上下文中github

@EnableSwagger2:启用swagger文档此注解也能够加在引导类,若是没有该注解,swagger文档将不会生效。spring

@Profile@ConditionalOnProperty两个注解用来作条件判断,在特定的条件下才加载swagger配置类。通常状况下,在生产环境中咱们须要禁用swagger文档,由于swagger文档会带来一些安全问题,咱们就利用上述两个条件装配注解来解决。下面来讲说这两个注解怎么使用?api

@Profile({"dev","test"}):只在开发、测试环境启用swagger文档。{"dev","test"}根据你在springboot中配置的多环境为准。安全

@ConditionalOnProperty(name = "swagger.enable",havingValue = "true"):只有在配置文件中添加了swagger.enable=true的配置环境才启用swagger文档。springboot

三、编写实体类

@Data
@ApiModel(value = "用户实体类")
public class User implements Serializable {

    @ApiModelProperty(value = "业务主键", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private int id;

    @ApiModelProperty(value = "名称", required = true)
    private String name;

    @ApiModelProperty(value = "手机号码", required = true)
    private String mobile;

    @ApiModelProperty(value = "电子邮箱", required = true)
    private String email;
}
复制代码

注解说明:app

@ApiModel:用来对类进行描述。主要参数说明:

参数 参数说明
value 类的名称
description 类的描述

@ApiModelProperty:用来对属性进行描述,主要参数说明

参数 参数说明
value 字段名称
name 容许覆盖的字段
dataType 参数的数据类型
required 是否必须
hidden 是否不在swagger中展现
accessMode 数据模式,只读、读写,使用的是AccessMode枚举类

四、编写controller

@RestController
@Api(tags = "用户管理", value = "用户管理")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @ApiOperation(value = "查询用户")
    @GetMapping(path = "/user")
    public ResultDTO findUser() {
        ResultDTO resultDTO = new ResultDTO();
        try {
            resultDTO.setSuccess(true);
            resultDTO.setModule(userService.findUser());
        } catch (Exception e) {
            logger.error(e.getMessage());
            resultDTO.setSuccess(false);
            resultDTO.setErrorCode("400");
            resultDTO.setErrorMsg(e.getMessage());
        }
        return resultDTO;
    }

    @ApiOperation(value = "新增用户")
    @PostMapping(path = "/user")
    public ResultDTO insertUser(@RequestBody User user) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            userService.insertUser(user);
            resultDTO.setSuccess(true);
        } catch (Exception e) {
            resultDTO.setSuccess(false);
            resultDTO.setErrorCode("400");
            resultDTO.setErrorMsg(e.getMessage());
            logger.error(e.getMessage());
        }
        return resultDTO;
    }

    @PutMapping(path = "/user")
    @ApiOperation(value = "更新用户",notes = "更新用户信息")
    public ResultDTO updateUser(@RequestBody User user) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            userService.updateUser(user);
            resultDTO.setSuccess(true);
        } catch (Exception e) {
            resultDTO.setSuccess(false);
            resultDTO.setErrorCode("400");
            resultDTO.setErrorMsg(e.getMessage());
            logger.error(e.getMessage());
        }
        return resultDTO;
    }

    @DeleteMapping(path = "/user/{id}")
    @ApiOperation(value = "删除用户", notes = "根据ID删除用户信息")
// @ApiImplicitParams({
// @ApiImplicitParam(value="用户id",name = "id",paramType="path")
// })
    public ResultDTO deleteUser(@ApiParam(value = "用户id",name = "id") @PathVariable(value = "id") int id) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            userService.deleteUser(id);
            resultDTO.setSuccess(true);
        } catch (Exception e) {
            resultDTO.setSuccess(false);
            resultDTO.setErrorCode("400");
            resultDTO.setErrorMsg(e.getMessage());
            logger.error(e.getMessage());
        }
        return resultDTO;
    }

    @DeleteMapping(path = "/user/ingorApi")
    @ApiIgnore(value = "我是别忽略的API接口,我将不会在Swagger上显示")
    public ResultDTO ignoreApi() {
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setSuccess(true);
        return resultDTO;
    }

}
复制代码

要是用swagger来作接口文档,须要在开发接口的时候添加一些接口注释,这样才能生成完整的接口文档。注解说明:

@Api:做用于类上,用来讲明类的做用,

@ApiOperation:做用在方法上用来对方法进行说明。主要参数:

参数 参数说明
value 方法的简要说明
tags 方法的主要功能
httpMethod 方法的请求类型,values["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS","PATCH"]

@ApiImplicitParams@ApiImplicitParam:用在方法上,对参数进行说明,@ApiImplicitParams包含多个@ApiImplicitParam,@ApiImplicitParam主要参数:

参数 参数说明
name 字段名称
value 字段描述
defaultValue 字段默认值
allowableValues 容许访问的值
required 是否填
dataType 数据类型
paramType 参数所在的位置[path、query、body、header、form]

@ApiParam:做用于单个参数,对于对参数的描述,主要参数说明:

参数 参数说明
name 字段名称
value 字段描述
defaultValue 字段默认值
allowableValues 容许访问的值
required 是否填
dataType 数据类型

@ApiIgnore:用来忽略该接口,加了@ApiIgnore的接口将不会在swagger文档上显示。

五、启动项目

访问http://127.0.0.1:8080/swagger-ui.html

若是你以为这界面不美观,OK,今天平头哥给你介绍一款更符合国人审美的ui框架swagger-ui-layer

结合swagger-ui-layer

要使用swagger-ui-layer只须要作一个改动,在pom.xml中作以下调整.

<!--注释掉springfox-swagger-ui-->
<!-- <dependency>-->
<!-- <groupId>io.springfox</groupId>-->
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
<!-- <version>2.9.2</version>-->
<!-- </dependency>-->
        <!--添加swagger-ui-layer-->
        <dependency>
            <groupId>com.github.caspar-chen</groupId>
            <artifactId>swagger-ui-layer</artifactId>
            <version>1.1.3</version>
        </dependency>
复制代码

从新启动项目,swagger-ui-layer的访问路径发生了变化,访问http://127.0.0.1:8080/docs.html,你将看到

界面是否是变得更加美观了,具体的使用就不在这里陈述了,体验一把就知道了。

更多关于swagger-ui-layer,点击这里

若是须要在一个swagger中集成多个项目,请参考程序员DD的博客:Spring Cloud Zuul中使用Swagger汇总API接口文档

demo下载:demo

我的公众号

相关文章
相关标签/搜索