目錄
上一篇文章我們學習了SpringBoot整合MyBatis-Plus,快速搭建了開發骨架。在最後測試接口的時候我們使用到了postman工具,雖然這個工具在使用起來非常方便,但還是不夠!尤其是在前後端分離盛行的今天,前後端開發人員在協作開發時,如果能有一個規範的標準的API文檔,就能夠大大減少溝通成本,進行高效的協作開發。
下面我們就開始學習今天的主角:SwaggerUI
一、框架介紹
SwaggerUI
- Swagger UI是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件。
常用註解
- @Api:用於修飾Controller類,生成Controller相關文檔信息
- @ApiOperation:用於修飾Controller類中的方法,生成接口方法相關文檔信息
- @ApiParam:用於修飾接口中的參數,生成接口參數相關文檔信息
- @ApiModelProperty:用於修飾實體類的屬性,當實體類是請求參數或返回結果時,直接生成相關文檔信息
爲什麼要使用SwaggerUI
現在多數的項目開發中,網站和移動端都需要進行數據交互和對接,這少不了使用REST編寫API接口這種場景。 特別是不同開發小組協作時,就更需要以規範和文檔作爲標準和協作基礎。良好的文檔可以減少溝通成本,達到事半功倍的效果。
有時對一些API說明的理解比較模糊,總想着能直接驗證一下自己的理解就好了,而不是需要去項目寫測試代碼來驗證自己的想法。 即API文檔應具備直接執行能力,這種能力類似word,wiki等是無法提供。 SwaggerUI就是這樣一種利器,基於html+javascript實現,傾向於在線文檔和測試,使用和集成十分簡單,能容易地生成不同模塊下的API列表, 每個API接口描述和參數、請求方法都能定製並直接測試得到直觀的響應數據。
體驗SwaggerUI最好的方法就是看下官網提供的demo,看過之後相信你一定會興奮不已。
官方體驗地址:http://petstore.swagger.io/
二、項目整合
這裏我們在上一篇文章SpringBoot整合MyBatis-Plus+Druid快速構建項目骨架的基礎上進行整合
添加項目依賴
在pom.xml文件中添加SwaggerUI依賴
<!-- swagger -->
<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>
新增SwaggerConfig.java配置類
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
//頁面展示信息設置
.apiInfo(apiInfo())
.select()
//爲當前包下controller生成API文檔
.apis(RequestHandlerSelectors.basePackage("com.ssymon.study.springbootstudy"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger在線文檔")
.description("SpringBootStudy API")
//聯繫人:名字 網址 郵箱
.contact(new Contact("SpringBootStudy","localhost:8080","[email protected]"))
//版本號
.version("1.0")
.build();
}
}
添加註解
在Student實體類中添加註解:@ApiModel , @ApiModelProperty
注意:這是裏爲了方便學習直接在實體類中添加對象註解,實際開發中儘量不了要使用entity作爲傳輸對象
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("STUDENT")
@ApiModel(value="Student對象", description="")
public class Student implements Serializable {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主鍵ID")
@TableId(value = "ID", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "姓名")
@TableField("NAME")
private String name;
@ApiModelProperty(value = "年齡")
@TableField("AGE")
private Integer age;
@ApiModelProperty(value = "性別:1-男,0-女")
@TableField("GENDER")
private Integer gender;
}
在StudentController控制類中添加註解:@Api , @ApiOperation,另外在寫幾個簡單的接口用來測試
@ApiOperation中幾個參數的含義
value:該接口的顯示名稱
httpMethod:該接口的http請求類型
response:該接口的返回類型
@RestController
@RequestMapping("/student")
@Api(value = "Student", tags = {"Student"})
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/listAll")
@ApiOperation(value = "查詢所有學生", httpMethod = "GET", response = List.class)
public List<Student> list() {
return studentService.list();
}
@PostMapping("/add")
@ApiOperation(value = "新增學生", httpMethod = "POST", response = String.class)
public String addStudent(@RequestBody Student student) {
studentService.save(student);
return "新增成功";
}
@DeleteMapping("/delete/{id}")
@ApiOperation(value = "根據ID刪除學生", httpMethod = "DETETE", response = String.class)
public String deleteStudent(@PathVariable @ApiParam("學生ID") Long id) {
studentService.removeById(id);
return "刪除成功";
}
@PutMapping("/edit")
@ApiOperation(value = "編輯學生", httpMethod = "PUT", response = String.class)
public String updateStudent(@RequestBody Student student) {
studentService.updateById(student);
return "編輯成功";
}
@GetMapping("/select/{id}")
@ApiOperation(value = "根據ID查詢學生", httpMethod = "GET", response = Student.class)
public Student getStudent(@PathVariable @ApiParam("學生ID") Long id) {
return studentService.getById(id);
}
}
啓動項目,查看結果
訪問地址:http://localhost:8080/sb-study/swagger-ui.html,
sb-study是我設置的項目路徑,沒設置的話可以訪問:http://localhost:8080/swagger-ui.html
我們點擊新增學生來接口測試一下,點擊之後展開如下圖
然後點擊右上角 Try it out,輸入參數,點擊Execute
然後就可以在下面看到接口返回結果
之後我們點擊根據ID查詢學生接口,輸入新增的ID,執行之後就可以看到返回信息
我們在測試接口是可以清晰的看到請求參數和返回參數中字段對應的解釋
接口方法入參:@RequestBody Student student 對應請求參數如下圖,前提是Student參數對象中添加了swagger註解
@ApiOperation註解的response參數:response = Student.class,對應返回參數如下圖,前提是Student參數對象中添加了swagger註解
小結
通過以上簡單的幾步,就能成功整合SwaggerUI。自己測試再也不用使用postman來測試接口了,項目經理再也不會來逼我寫接口文檔了,前端小夥伴再也不會來問我那個字段是啥意思了。
API Developmentfor Everyone
SwaggerUI官網:https://swagger.io/