https://swagger.io/
相信无论是前端还是后端开发,都或多或少地被接口文档折磨过,期望有一个好的接口文档。Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

Swagger
框架说明及使用
Swagger官网中提供了一系列的组件,可以在线边写接口文档。

Swagger 组件
开源版
- Swagger Codegen: 通过Codegen 可以将描述文件生成html格式和cwiki形式的接口文档,同时也能生成多钟语言的服务端和客户端的代码。支持通过jar包,docker,node等方式在本地化执行生成。也可以在后面的Swagger Editor中在线生成。
- Swagger Editor: 类似于markendown编辑器的编辑Swagger描述文件的编辑器,该编辑支持实时预览描述文件的更新效果。也提供了在线编辑器和本地部署编辑器两种方式。
- Swagger UI:提供了一个可视化的UI页面展示描述文件。接口的调用方、测试、项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求。该项目支持在线导入描述文件和本地部署UI项目。
专业版
- Swagger Inspector: 感觉和postman差不多,是一个可以对接口进行测试的在线版的postman。比在Swagger UI里面做接口请求,会返回更多的信息,也会保存你请求的实际请求参数等数据。
- SwaggerHub:集成了上面所有项目的各个功能,你可以以项目和版本为单位,将你的描述文件上传到Swagger Hub中。在Swagger Hub中可以完成上面项目的所有工作,需要注册账号,分免费版和收费版。
- SwaggerHub Enterprise:为企业打造的Swagger扩展,使团队协作开发API。SwaggerHub Enterprise可在云和本地安装中使用。
基于Spring框架的Swagger
http://springfox.github.io/springfox/
- Springfox Swagger: Spring 基于swagger规范,可以将基于SpringMVC和Spring Boot项目的项目代码,自动生成JSON格式的描述文件。本身不是属于Swagger官网提供的。
SpringBoot整合Swagger2
添加相关依赖
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger2.version}</version> </dependency>
|
配置Swagger2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| @Configuration @EnableSwagger2 public class SwaggerConfig {
@Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("net.ling.security")) .paths(PathSelectors.any()) .build(); }
private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Security开发安全的REST服务") .description("Swagger文档") .contact(new Contact("https://lingmoumou.github.io/", null, null)) .version("1.0.0") .build(); } }
|
创建测试实例
启动程序
![Swagger页面]()
Swagger页面
SpringSecurity中使用Swagger2
开放Swagger的权限
1 2 3 4 5 6 7 8 9 10 11 12 13
|
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring(). antMatchers("/swagger-ui.html") .antMatchers("/webjars/**") .antMatchers("/v2/**") .antMatchers("/swagger-resources/**"); }
}
|
Swagger2相关常用注解
- @Api:用在类上,说明该类的作用。
- @ApiOperation:注解来给API增加方法说明。
- @ApiImplicitParams: 用在方法上包含一组参数说明。
- @ApiImplicitParam:用来注解来给方法入参增加说明。
- @ApiResponses:用于表示一组响应
- @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
- code:数字,例如400
- message:信息,例如”请求参数没填好”
- response:抛出异常的类
- @ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
- @ApiModelProperty:描述一个model的属性
参考文献