springmvc+swagger构建Restful风格文档

时间:2023-03-08 20:53:22

  本次和大家分享的是java方面的springmvc来构建的webapi接口+swagger文档;上篇文章分享.net的webapi用swagger来构建文档,因为有朋友问了为啥.net有docpage文档你还用swagger,这里主要目的是让接口文档统一,当操作多种开发语言做接口时,如果有统一风格的api文档是不是很不错;还有就springcloude而言,微服务如果有很多的话,使用swagger自动根据服务serverid来加载api文档是很方便的。swagger设置比较简单,为了今后查找资料和使用方便故此记录下

  • 准备工作
  • 快速构建api文档
  • 常用的细节
  1. 过滤默认错误api
  2. 添加授权token列
  3. 添加上传文件列

准备工作

  首选需要一个springmvc项目,这里我用的是springboot+maven来快速构建, 要使用swagger只需要在maven中添加依赖包就行:

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

  然后创建一个UserController,然后再定义个Login的Action,定义请求和响应实体,由于api接口需要对请求和响应属性列做 文字描述,并且上面我们在项目中加了swagger包,因此以直接在实体和Action使用特性来增加具体文字描述:

 @RestController
@Api(tags = "会员接口")
public class UserController { @PostMapping("/login")
@ApiOperation(value = "登录")
public LoginRp login(@RequestBody LoginRq rq) {
LoginRp rp = new LoginRp(); if (rq.getUserName().isEmpty() || rq.getUserPwd().isEmpty()) {
rp.setCode(EmApiCode.登录账号或密码不能为空.getVal());
return rp;
} if (rq.getUserName().equals("shenniu001") && rq.getUserPwd().equals("")) {
rp.setCode(EmApiCode.成功.getVal()); rp.setToken(UUID.randomUUID().toString());
} else {
rp.setCode(EmApiCode.失败.getVal());
}
return rp;
} }

  请求和响应实体类:

 @ApiModel
public class LoginRq implements Serializable{ private static final long serialVersionUID = -158328750073317876L; @ApiModelProperty(value = "登录账号")
private String userName; @ApiModelProperty(value = "登录密码")
private String userPwd; } @ApiModel
public class LoginRp extends BaseRp implements Serializable {
private static final long serialVersionUID = -1486838360296425228L; @ApiModelProperty(value = "授权token")
private String token; public String getToken() {
return token;
} public void setToken(String token) {
this.token = token;
}
}

  注解简单说明:

  @Api:同一类接口的总描述,一般用于Controller标记

  @ApiOperation(value = "登录"):在Action上标记,描述这个Action接口具体干什么

  @ApiModel:请求响应实体类class上的标记

  @ApiModelProperty(value = "登录账号"):请求响应属性上的标记,用来描述该属性具体说明

快速构建api文档

  准备做完后要生成文档,还需要自定义两个封装类,如下Swagger2类:

 @Configuration
@EnableSwagger2
public class Swagger2 { @Bean
public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2)
.select()
//过滤默认错误api
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.apiInfo(apiInfo());
} //常用的细节
//过滤指定的action
//添加授权token列
//添加上传文件列
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("开车接口文档")
.description("该文档只允许我使用")
//版本
.version("0.0.0.1")
.contact("作者:841202396@qq.com")
.build();
}
}

  这个类主要初始化一些全局文档的说明和版本并且构架api文档;上面是生成文档,但是具体文档数据源用从swagger的SwaggerResourcesProvider中来,因此自定义的DocumentationConfig类实现SwaggerResourcesProvider接口,如下:

 @Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
resources.add(swaggerResource("开车接口api", "/v2/api-docs", "0.0.0.1"));
resources.add(swaggerResource("坐车接口api", "/v2/api-docs", "0.0.0.1"));
return resources;
} private SwaggerResource swaggerResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}

  主要加载文档的数据源,数据源主要通过 resources.add(swaggerResource("坐车接口api", "/v2/api-docs", "0.0.0.1")) 添加,倘若你想添加其他api接口源就可以在这里进行配置,直接把/v2/api-docs改成你的url就行,这个地方也是springcloud微服务api添加的入口;当编码完成后我们来看看效果:

  springmvc+swagger构建Restful风格文档

  能成功加载出我们的login接口,而且有一些说明性的文字;再来看看我们请求和响应的参数是否有说明:

  springmvc+swagger构建Restful风格文档

  请求和响应都有了相应的说明,是不是挺简单;

常用的细节

  1.过滤默认错误api

  由于springmvc封装有错误的controller,因此swagger也会把这个展示出来,因为是扫描的所有controller来展示swagger文档的,故此我们需要屏蔽这些对于对接方没用的接口;这里通过设置paths的不匹配就行了,以下代码:

 //过滤默认错误api
paths(Predicates.not(PathSelectors.regex("/error.*")))

  2.添加授权token列

  对于接口验证来说通常需要个token并且放在header里面,这里我们直接在swagger上增加一个显示的token,只需要在build之前增加一个header参数:

 @Bean
public Docket createRestApi() { List<Parameter> pars = new ArrayList<>();
//添加授权token
ParameterBuilder tokenPar = new ParameterBuilder();
tokenPar.name("token").description("授权token 注:登录不需要填,只有post方式的接口必填").
modelRef(new ModelRef("string")).
parameterType("header").required(false).build();
pars.add(tokenPar.build()); return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.globalOperationParameters(pars)
.apiInfo(apiInfo());
}

  这个时候每个action接口文档块中都会增加一个token列,type是header类型:

  springmvc+swagger构建Restful风格文档

  3.添加上传文件列

  通常api接口都包含一个公共上传接口,为了让swagger文档更方便,我们需要让她支持下上传;首先这样定义一个上传接口:

 @PostMapping(value = "/upload",headers = "content-type=multipart/form-data")
@ApiOperation(value = "上传")
public BaseRp upload(@ApiParam(value = "上传的文件",required = true) @RequestBody MultipartFile file) {
BaseRp rp = new BaseRp(); rp.setMessage("上传文件名:"+file.getOriginalFilename()); return rp;
}

  其他就不用再设置了,仅仅如此运行后效果:

  springmvc+swagger构建Restful风格文档

  咋们点击“选择文件”测试下上传,点击try能够得到如下成功运行的效果图:

  springmvc+swagger构建Restful风格文档