文檔向來在軟件開發過程中的每一個階段都是非常重要的,如果沒有文檔,那軟件的可維護性就會變得很糟,以致于影響可擴展性,最后慢慢的使軟件變成一堆亂糟糟的無用的代碼。而不同系統之間的接口文檔其重要性更顯而易見,一般常用的接口文檔采用以下形式:
- [ ]
口口相傳 - [x] 用world或其他文本文件進行保存
- [x] 用wiki編寫
上面這些方式都有各自的缺點,比如不易維護,不易測試接口,接口變更而文檔未能同步更新等。但Swagger的出現改變了這些情形,Swagger的文檔編寫相當于就是在寫代碼,在更改接口代碼的同時就能方便的更新文檔,還能方便的進行接口的測試,怎么樣,很心動吧,心動不如行動,那我們開始練習吧。
創建一個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的描述信息:
有注解能對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:對復雜類型字段進行說明
寫了這么多,讓我們看看最終的效果圖吧:
這就是最終出來的文檔頁面,那個Try it out!
按鈕是用來進行接口測試的,你可以填入參數進行測試。
最后貼上工程代碼:
project code
如果用markdown編寫文章的話,強烈推薦小書匠,真的很好用,這篇文章就是用那個寫出來的?