本文介绍如何使用Swagger2编写API文档
前言
通过文章你可以了解到:
- 了解Swagger
- 如何使用Swagger编写API文档
- 掌握使用swagger编写API文档
介绍
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
浏览 Swagger-Spec 去了解更多关于Swagger 项目的信息,包括附加的支持其他语言的库。
集成Swagger到项目
1.导入相关依赖
<!-- 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>
2.配置Swagger类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// swagger开关,开发环境开启,生产环境关闭
@Value("${swagger.enabled}")
private boolean enableSwagger;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//是否开启 (true 开启 false隐藏。生产环境建议隐藏)
.enable(enableSwagger)
.select()
//扫描的路径包,设置basePackage会将包下的所有被@Api标记类的所有方法作为api
.apis(RequestHandlerSelectors.basePackage("com.springswagger.controller"))
//指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any())
.build();
}
/**
* @Description swagger基本信息
* @Param
* @return
* @Author zhen.ma
* @Date 2020.06.11 22:26
**/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//设置文档标题(API名称)
.title("SpringBoot使用Swagger2构建restful Api文档")
//文档描述
.description("接口说明")
//服务条款URL
.termsOfServiceUrl("http://127.0.0.1:8080/")
//联系信息
.contact(new Contact("xiao.ge","http://xiao.ge.com","3311247943@qq.com"))
//版本号
.version("V1.0")
.build();
}
//swagger接口文档界面
//http://localhost:8080/swagger-ui.html
}
3.添加测试类控制器
@RestController
@RequestMapping("api/v1")
@Api(value = "测试接口", tags = "UserController", description = "测试接口相关")
public class MyController {
@GetMapping("/")
@ApiOperation(value = "访问网站首页", notes = "网站首页")
public void index() {
}
@GetMapping(value = "/mi", produces = "application/json")
@ApiImplicitParam(name = "num", value = "数字", required = true, dataType = "int", paramType = "query")
@ApiOperation(value = "一个数的平方", notes = "求一个数的平方")
public int getNum2(@RequestParam int num) {
return num*num;
}
}
访问可视化web页面
- api文档访问 http://localhost:8080/swagger-ui.html
常用注解
注解 | 位置 |
---|---|
@Api() | 类 |
@ApiOperation() | 方法 |
@ApiParam() | 说明方法,参数和字段的用处 |
@ApiModel() | 实体类 |
@ApiModelProperty() | 说明属性 |
@ApiIgnore() | 标注可忽略的类,方法和参数 |
@ApiImplicitParam() | 方法的单个请求参数 |
@ApiImplicitParams() | 包含多个 @ApiImplicitParam |