一,简述
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。可以作为REST APIs的交互式文档,也可以作为REST APIs的形式化的接口描述,生成客户端和服务端的代码。
二,编写API的发方式
1,定义YAML文件,然后可以生成各种语言的代码框架,对于后台程序员来说,较少人会愿意写出一堆YAML格式。
2,定义JSON格式文件,按照swagger文档书写规范编写文档,和YAML一样只是两种不同格式。
3,通过swagger的各种语言的插件,可以通过配置及少量代码,生成接口文档及测试界面。通过yaml或json书写的是静态文档,需要书写文档中需要的内容,完成后可以通过可视化页面显示接口文档。但要完成整个项目的接口文档书写也非常耗时,如果是后台开发,可以通过简单配置实现文档的自动生成。
本文使用的是第三种方式,也是开发人员最常用的方式,在代码中使用简单的配置自动生成API文档。
三,相关jar包
spring boot版本: 2.2.1.RELEASE
compile ('io.springfox:springfox-swagger2:2.9.2')
compile ('io.springfox:springfox-swagger-ui:2.9.2')
四,详细实例
1,swagger配置类(还有其他好多参数没有配置,配置了一些自认为比较有用的配置)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class SwaggerConf {
//http://localhost:8080/swagger-ui.html#
@Bean
public Docket createRestApi() {
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
ticketPar.name(HttpHeaders.AUTHORIZATION)//创建headers name(key) --1
.description(Constant.BASIC) //description info --2
.modelRef(new ModelRef("String")).parameterType("header") // type
.required(false).defaultValue("basic #####") // 不是必须,默认值
.build();
pars.add(ticketPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.controller")) //生成swagger的路径,一般为controller
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars);
}
//swagger的一些信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger API")
.description("These apis is used to test swagger.")
.version("1.0")
.build();
}
}
代码生成的页面对比:
2,controller层配置
post实例:
@Api(tags = "Swagger API")
@Log4j2
@RestController
public class SwaggerController {
@PostMapping("/v1/test01")
@ApiOperation("swagger post test.")
@ApiResponses({
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 500, message = "Internal Server Error")
})
public ResponseEntity<ResponseStatusDto> set(@Valid @RequestBody SwaggerTest1 dto,
@ApiIgnore @RequestAttribute(name = "user_name") String userName
) {
return new ResponseEntity<>(HttpStatus.Ok);
}
@GetMapping("/v1/swagger/{param_type}/{value}")
@ApiImplicitParams({
@ApiImplicitParam(name = "param_type", defaultValue = "name",
required = true, dataType = "String", paramType = "path"),
@ApiImplicitParam(name = "value", defaultValue = "HPqOGvAAsYV66E",
required = true, dataType = "String", paramType = "path")
})
public ResponseEntity<ResponseStatusDto> get(@PathVariable("param_type") @NotNull String paramType,
@PathVariable @NotNull String value,
@ApiIgnore @RequestAttribute(name = "user_name") String userName)
{
return new ResponseEntity<>(HttpStatus.Ok);
}
}
package com.swagger.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Data
@ApiModel
public class OneTimeRequestDto implements Serializable {
private static final long serialVersionUID = 2597547944454691103L;
@NotNull
@ApiModelProperty(name = "param_type", example = "name", required = true)
@JsonProperty(value = "param_type")
private String paramType;
@NotNull
@ApiModelProperty(name = "value", example = "qOGvAAsYV66E", required = true)
private String value;
}
@Api: 修饰整个类,描述Controller的作用,tag属性用做一个标记
@ApiOperation:描述一个类的一个方法,或者说一个接口,括号里面为此接口的描述信息
@ApiImplicitParams: 请求参数说明,一般为跟在path的参数,多个里面跟@ApiImplicitParam
@ApiModel: 描述用对象来接受参数的对象,一般为body
@ApiModelProperty: 对对象的每个参数进行描述
@ApiResponses: 对response信息进行描述,多个可在里面跟@ApiResponse
@ApiIgnore: 忽略此接口或者此此参数
然后启动项目访问http://localhost:8080/swagger-ui.html#就可以看到我们这个项目的API文档。
更详细的参考:https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/