Swagger入门
文档向来在软件开发过程中的每一个阶段都是非常重要的,如果没有文档,那软件的可维护性就会变得很糟,以致于影响可扩展性,最后慢慢的使软件变成一堆乱糟糟的无用的代码。而不同系统之间的接口文档其重要性更显而易见,一般常用的接口文档采用以下形式:
- [ ]
口口相传 - [x] 用world或其他文本文件进行保存
- [x] 用wiki编写
上面这些方式都有各自的缺点,比如不易维护,不易测试接口,接口变更而文档未能同步更新等。但Swagger的出现改变了这些情形,Swagger的文档编写相当于就是在写代码,在更改接口代码的同时就能方便的更新文档,还能方便的进行接口的测试,怎么样,很心动吧,心动不如行动,那我们开始练习吧。
创建一个Spring boot工程:
Spring boot工程目录加入Swagger依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
写一个controller作为API接口:
@RestController
@RequestMapping("/demo")
public class DemoController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public User addUser(@RequestBody @Valid User user){
user.setDescription("had been dealed");
return user;
}
@RequestMapping(value="/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity delete(@PathVariable Integer id){
//mock deleted;
return new ResponseEntity("User had been deleted", HttpStatus.OK);
}
@RequestMapping(value = "/show", method= RequestMethod.GET)
public User showUser(@RequestParam("id") Integer id){
User user = new User();
user.setId(1);
user.setDescription("show user");
user.setAge(100);
user.setUsername("test");
return user;
}
}
这个和普通controller没有撒区别,而我们想要让它生成出接口文档,并且能够供别人进行接口测试,就需要进行Swagger的配置及其相关的注解的帮助了。
配置Swagger
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
//指定要生成api文档的根包
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
//路径配置
.paths(regex("/demo.*"))
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger2的Restful API 文档")
.description("Spring Boot和Swagger的结合")
.version("1.0")
.build();
}
}
配置好后,就可以启动你的spring boot 应用,先一睹swagger的芳容,进入这个地址:http://localhost:8000/swagger-ui.html
,具体的服务器端口号撒的根据你本地的进行更改,然后就会看到这个页面:
但是,虽然能看到文档页面了,但这还比较简陋,各个Restful方法的具体文档都还没有,这些还得靠我们去代码里加入,毕竟还不是那么智能的,怎么加入呢,请接着往下看。
用@Api
在Controller类上定义这个服务的描述信息,像这样:
@RestController
@RequestMapping("/demo")
@Api(value="demo", description="这是一个Swagger demo的服务")
public class DemoController {
.....
}
然后在swagger ui里面就看到了对这个controller的描述信息:
@Api in controller class有注解能对controller进行描述,当然也有注解能对里面的各个方法进行描述,这就是@ApiOperation
和它的小伙伴们:
@RequestMapping(value = "/add", method = RequestMethod.POST,produces = "application/json")
@ApiOperation(value = "新增一个用户", response = User.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功保存"),
@ApiResponse(code = 401, message = "你没权限"),
@ApiResponse(code = 403, message = "你被禁止访问了"),
@ApiResponse(code = 404, message = "没找到,哈哈哈")
}
)
@ApiImplicitParam(name = "user",
value = "要新增的用户",
dataType = "User",//This can be the class name or a primitive
required = true,
paramType = "body")
public User addUser(@RequestBody @Valid User user){
user.setDescription("had been dealed");
return user;
}
@RequestMapping(value="/delete/{id}", method = RequestMethod.DELETE,produces = "application/json")
@ApiOperation(value = "删除一个用户", response = ResponseEntity.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功保存"),
@ApiResponse(code = 401, message = "你没权限"),
@ApiResponse(code = 403, message = "你被禁止访问了"),
@ApiResponse(code = 404, message = "没找到,哈哈哈")
}
)
@ApiImplicitParam(name="id",
value = "要删除的用户id",
dataType = "int",//This can be the class name or a primitive
required = true,
paramType = "path")//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
public ResponseEntity delete(@PathVariable Integer id){
//mock deleted;
return new ResponseEntity("User had been deleted", HttpStatus.OK);
}
@RequestMapping(value = "/show", method= RequestMethod.GET,produces = "application/json")
@ApiOperation(value = "显示一个用户", response = ResponseEntity.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功保存"),
@ApiResponse(code = 401, message = "你没权限"),
@ApiResponse(code = 403, message = "你被禁止访问了"),
@ApiResponse(code = 404, message = "没找到,哈哈哈")
}
)
@ApiImplicitParams({
@ApiImplicitParam(name="id",
value = "要删除的用户id",
dataType = "int",//This can be the class name or a primitive
required = true,
paramType = "query"),//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
@ApiImplicitParam(name = "param",
value = "其他参数",
dataType = "String",//This can be the class name or a primitive
required = true,
paramType = "query")//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
})
public User showUser(@RequestParam("id") Integer id,@RequestParam("param") String otherParam){
User user = new User();
user.setId(1);
user.setDescription("show user");
user.setAge(100);
user.setUsername("test");
return user;
}
当参数是复杂类型(非原始类或及其包装类)时,就需要用到@ApiModel
和@ApiModelProperty
:
@Data
@ApiModel
public class User {
@ApiModelProperty(notes = "用户id",required = false,dataType="Integer")
private Integer id;
@NotBlank
@ApiModelProperty(notes = "用户名",required = true,dataType="String")
private String username;
@NotNull
@Max(100)
@Min(1)
@ApiModelProperty(notes = "年龄",required = true,dataType="Integer",allowableValues = "range[0,100]")
private Integer age;
@ApiModelProperty(notes = "描述",required = false,dataType="String")
private String description;
}
注解说明:
@ApiOperation:对方法进行描述,说明方法作用
@ApiResponses:表示一组响应
@ApiImplicitParams:对方法的多个参数进行描述
@ApiImplicitParam:对单个的参数进行描述(name:参数名,value:参数的描述,dataType:参数类型,required:是否必须,paramType:参数来源方式)
@ApiModel:对复杂类型参数进行说明
@ApiModelProperty:对复杂类型字段进行说明
写了这么多,让我们看看最终的效果图吧:
final这就是最终出来的文档页面,那个Try it out!
按钮是用来进行接口测试的,你可以填入参数进行测试。
最后贴上工程代码:
project code
如果用markdown编写文章的话,强烈推荐小书匠,真的很好用,这篇文章就是用那个写出来的☺