隨着前後端分離架構和微服務架構的流行,我們使用Spring Boot來構建RESTful API項目的場景越來越多。通常我們的一個RESTful API就有可能要服務於多個不同的開發人員或開發團隊:IOS開發、Android開發、Web開發甚至其他的後端服務等。爲了減少與其他團隊平時開發期間的頻繁溝通成本,傳統做法就是創建一份RESTful API文檔來記錄所有接口細節,然而這樣的做法有以下幾個問題:
- 由於接口衆多,並且細節複雜(需要考慮不同的HTTP請求類型、HTTP頭部信息、HTTP請求內容等),高質量地創建這份文檔本身就是件非常吃力的事,下游的抱怨聲不絕於耳。
- 隨着時間推移,不斷修改接口實現的時候都必須同步修改接口文檔,而文檔與代碼又處於兩個不同的媒介,除非有嚴格的管理機制,不然很容易導致不一致現象。
爲了解決上面這樣的問題,本文將介紹RESTful API的重磅好夥伴Swagger2,它可以輕鬆的整合到Spring Boot中,並與Spring MVC程序配合組織出強大RESTful API文檔。它既可以減少我們創建文檔的工作量,同時說明內容又整合入實現代碼中,讓維護文檔和修改代碼整合爲一體,可以讓我們在修改代碼邏輯的同時方便的修改文檔說明。另外Swagger2也提供了強大的頁面測試功能來調試每個RESTful API。具體效果如下圖所示:
下面來具體介紹,在Spring Boot中使用我們自己實現的starter來整合Swagger。該整合項目的Github:https://github.com/SpringForAll/spring-boot-starter-swagger。如果您覺得它好用,歡迎Star支持我們!
準備工作
首先,我們需要一個Spring Boot實現的RESTful API工程,若您沒有做過這類內容,建議先閱讀上一篇教程:
Spring Boot 2.x基礎教程:構建RESTful API與單元測試構建一個。或者也可以直接使用上一篇教程中的樣例作爲基礎,即下面倉庫中的chapter2-1
工程:
- Github:https://github.com/dyc87112/SpringBoot-Learning/tree/2.x
- Gitee:https://gitee.com/didispace/SpringBoot-Learning/tree/2.x
整合Swagger2
下面,我們以上面倉庫中的chapter2-1
工程進行整合改造。
第一步:添加swagger-spring-boot-starter依賴
在pom.xml
中加入依賴,具體如下:
<dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.9.0.RELEASE</version> </dependency> |
第二步:應用主類中添加@EnableSwagger2Doc
註解,具體如下
@EnableSwagger2Doc @SpringBootApplication public class Chapter22Application { public static void main(String[] args) { SpringApplication.run(Chapter22Application.class, args); } } |
第三步:application.properties
中配置文檔相關內容,比如
swagger.title=spring-boot-starter-swagger swagger.description=Starter for swagger 2.x swagger.version=1.4.0.RELEASE swagger.license=Apache License, Version 2.0 swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger swagger.contact.name=didi swagger.contact.url=http://blog.didispace.com [email protected] swagger.base-package=com.didispace swagger.base-path=/** |
各參數配置含義如下:
swagger.title
:標題swagger.description
:描述swagger.version
:版本swagger.license
:許可證swagger.licenseUrl
:許可證URLswagger.termsOfServiceUrl
:服務條款URLswagger.contact.name
:維護人swagger.contact.url
:維護人URLswagger.contact.email
:維護人emailswagger.base-package
:swagger掃描的基礎包,默認:全掃描swagger.base-path
:需要處理的基礎URL規則,默認:/**
更多配置說明可見官方說明:https://github.com/SpringForAll/spring-boot-starter-swagger
第四步:啓動應用,訪問:http://localhost:8080/swagger-ui.html
,就可以看到如下的接口文檔頁面:
添加文檔內容
在整合完Swagger之後,在http://localhost:8080/swagger-ui.html
頁面中可以看到,關於各個接口的描述還都是英文或遵循代碼定義的名稱產生的。這些內容對用戶並不友好,所以我們需要自己增加一些說明來豐富文檔內容。如下所示,我們通過@Api
,@ApiOperation
註解來給API增加說明、通過@ApiImplicitParam
、@ApiModel
、@ApiModelProperty
註解來給參數增加說明。
比如下面的例子:
@Api(tags = "用戶管理") @RestController @RequestMapping(value = "/users") // 通過這裏配置使下面的映射都在/users下 public class UserController { // 創建線程安全的Map,模擬users信息的存儲 static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>()); @GetMapping("/") @ApiOperation(value = "獲取用戶列表") public List<User> getUserList() { List<User> r = new ArrayList<>(users.values()); return r; } @PostMapping("/") @ApiOperation(value = "創建用戶", notes = "根據User對象創建用戶") public String postUser(@RequestBody User user) { users.put(user.getId(), user); return "success"; } @GetMapping("/{id}") @ApiOperation(value = "獲取用戶詳細信息", notes = "根據url的id來獲取用戶詳細信息") public User getUser(@PathVariable Long id) { return users.get(id); } @PutMapping("/{id}") @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "用戶編號", required = true, example = "1") @ApiOperation(value = "更新用戶詳細信息", notes = "根據url的id來指定更新對象,並根據傳過來的user信息來更新用戶詳細信息") public String putUser(@PathVariable Long id, @RequestBody User user) { User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @DeleteMapping("/{id}") @ApiOperation(value = "刪除用戶", notes = "根據url的id來指定刪除對象") public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; } } @Data @ApiModel(description="用戶實體") public class User { @ApiModelProperty("用戶編號") private Long id; @ApiModelProperty("用戶姓名") private String name; @ApiModelProperty("用戶年齡") private Integer age; } |
完成上述代碼添加後,啓動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html
,就能看到下面這樣帶中文說明的文檔了(其中標出了各個註解與文檔元素的對應關係以供參考):
API文檔訪問與調試
在上圖請求的頁面中,我們看到user的Value是個輸入框?是的,Swagger除了查看接口功能外,還提供了調試測試功能,我們可以點擊上圖中右側的Model Schema(黃色區域:它指明瞭User的數據結構),此時Value中就有了user對象的模板,我們只需要稍適修改,點擊下方“Try it out!”
按鈕,即可完成了一次請求調用!
此時,你也可以通過幾個GET請求來驗證之前的POST請求是否正確。
相比爲這些接口編寫文檔的工作,我們增加的配置內容是非常少而且精簡的,對於原有代碼的侵入也在忍受範圍之內。因此,在構建RESTful API的同時,加入Swagger來對API文檔進行管理,是個不錯的選擇。