swagger生成接口文檔

1:認識Swagger

Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作爲服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。

 作用:

    1. 接口的文檔在線自動生成。

    2. 功能測試。

 Swagger是一組開源項目,其中主要要項目如下:

1.   Swagger-tools:提供各種與Swagger進行集成和交互的工具。例如模式檢驗、Swagger 1.2文檔轉換成Swagger 2.0文檔等功能。

2.   Swagger-core: 用於Java/Scala的的Swagger實現。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進行集成。

3.   Swagger-js: 用於JavaScript的Swagger實現。

4.   Swagger-node-express: Swagger模塊,用於node.js的Express web應用框架。

5.   Swagger-ui:一個無依賴的HTML、JS和CSS集合,可以爲Swagger兼容API動態生成優雅文檔。

6.   Swagger-codegen:一個模板驅動引擎,通過分析用戶Swagger資源聲明以各種語言生成客戶端代碼。

 

2:Maven

版本號請根據實際情況自行更改。

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger2</artifactId>

    <version>2.2.2</version>

</dependency>

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger-ui</artifactId>

    <version>2.2.2</version>

</dependency>

 

3:創建Swagger2配置類

在Application.java同級創建Swagger2的配置類Swagger2

  1. package com.swaggerTest;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import springfox.documentation.builders.ApiInfoBuilder;
  5. import springfox.documentation.builders.PathSelectors;
  6. import springfox.documentation.builders.RequestHandlerSelectors;
  7. import springfox.documentation.service.ApiInfo;
  8. import springfox.documentation.spi.DocumentationType;
  9. import springfox.documentation.spring.web.plugins.Docket;
  10. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  11. /**
  12. * Swagger2配置類
  13. * 在與spring boot集成時,放在與Application.java同級的目錄下。
  14. * 通過@Configuration註解,讓Spring來加載該類配置。
  15. * 再通過@EnableSwagger2註解來啓用Swagger2。
  16. */
  17. @Configuration
  18. @EnableSwagger2
  19. public class Swagger2 {
  20. /**
  21. * 創建API應用
  22. * apiInfo() 增加API相關信息
  23. * 通過select()函數返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展現,
  24. * 本例採用指定掃描的包路徑來定義指定要建立API的目錄。
  25. *
  26. * @return
  27. */
  28. @Bean
  29. public Docket createRestApi() {
  30. return new Docket(DocumentationType.SWAGGER_2)
  31. .apiInfo(apiInfo())
  32. .select()
  33. .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))
  34. .paths(PathSelectors.any())
  35. .build();
  36. }
  37. /**
  38. * 創建該API的基本信息(這些基本信息會展現在文檔頁面中)
  39. * 訪問地址:http://項目實際地址/swagger-ui.html
  40. * @return
  41. */
  42. private ApiInfo apiInfo() {
  43. return new ApiInfoBuilder()
  44. .title("Spring Boot中使用Swagger2構建RESTful APIs")
  45. .description("更多請關注http://www.baidu.com")
  46. .termsOfServiceUrl("http://www.baidu.com")
  47. .contact("sunf")
  48. .version("1.0")
  49. .build();
  50. }
  51. }

如上代碼所示,通過createRestApi函數創建Docket的Bean之後,apiInfo()用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。

 

4:添加文檔內容

在完成了上述配置後,其實已經可以生產文檔內容,但是這樣的文檔主要針對請求本身,描述的主要來源是函數的命名,對用戶並不友好,我們通常需要自己增加一些說明來豐富文檔內容。

 

Swagger使用的註解及其說明:

@Api:用在類上,說明該類的作用。

@ApiOperation:註解來給API增加方法說明。

@ApiImplicitParams : 用在方法上包含一組參數說明。

@ApiImplicitParam:用來註解來給方法入參增加說明。

@ApiResponses:用於表示一組響應

@ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應信息

    l   code:數字,例如400

    l   message:信息,例如"請求參數沒填好"

    l   response:拋出異常的類   

@ApiModel:描述一個Model的信息(一般用在請求參數無法使用@ApiImplicitParam註解進行描述的時候)

    l   @ApiModelProperty:描述一個model的屬性

 

注意:@ApiImplicitParam的參數說明:

paramType:指定參數放在哪個地方

header:請求參數放置於Request Header,使用@RequestHeader獲取

		<p>query:請求參數放置於請求地址,使用@RequestParam獲取</p>

		<p>path:(用於restful接口)--&gt;請求參數的獲取:@PathVariable</p>

		<p>body:(不常用)</p>

		<p>form(不常用)</p>
		</td>
	</tr><tr><td>
		<p>name:參數名</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr><tr><td>
		<p>dataType:參數類型</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr><tr><td>
		<p>required:參數是否必須傳</p>
		</td>
		<td>
		<p>true | false</p>
		</td>
	</tr><tr><td>
		<p>value:說明參數的意思</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr><tr><td>
		<p>defaultValue:參數的默認值</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr></tbody></table></div><p><strong><span style="color:#ff0000;"><em>例子:</em></span></strong></p>
  1. package com.swaggerTest.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.util.StringUtils;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestMethod;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import io.swagger.annotations.Api;
  9. import io.swagger.annotations.ApiImplicitParam;
  10. import io.swagger.annotations.ApiImplicitParams;
  11. import io.swagger.annotations.ApiOperation;
  12. /**
  13. * 一個用來測試swagger註解的控制器
  14. * 注意@ApiImplicitParam的使用會影響程序運行,如果使用不當可能造成控制器收不到消息
  15. *
  16. * @author SUNF
  17. */
  18. @Controller
  19. @RequestMapping("/say")
  20. @Api(value = "SayController|一個用來測試swagger註解的控制器")
  21. public class SayController {
  22. @ResponseBody
  23. @RequestMapping(value ="/getUserName", method= RequestMethod.GET)
  24. @ApiOperation(value="根據用戶編號獲取用戶姓名", notes="test: 僅1和2有正確返回")
  25. @ApiImplicitParam(paramType="query", name = "userNumber", value = "用戶編號", required = true, dataType = "Integer")
  26. public String getUserName(@RequestParam Integer userNumber){
  27. if(userNumber == 1){
  28. return "張三丰";
  29. }
  30. else if(userNumber == 2){
  31. return "慕容復";
  32. }
  33. else{
  34. return "未知";
  35. }
  36. }
  37. @ResponseBody
  38. @RequestMapping("/updatePassword")
  39. @ApiOperation(value="修改用戶密碼", notes="根據用戶id修改密碼")
  40. @ApiImplicitParams({
  41. @ApiImplicitParam(paramType="query", name = "userId", value = "用戶ID", required = true, dataType = "Integer"),
  42. @ApiImplicitParam(paramType="query", name = "password", value = "舊密碼", required = true, dataType = "String"),
  43. @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密碼", required = true, dataType = "String")
  44. })
  45. public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password,
  46. @RequestParam(value="newPassword") String newPassword){
  47. if(userId <= 0 || userId > 2){
  48. return "未知的用戶";
  49. }
  50. if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
  51. return "密碼不能爲空";
  52. }
  53. if(password.equals(newPassword)){
  54. return "新舊密碼不能相同";
  55. }
  56. return "密碼修改成功!";
  57. }
  58. }

完成上述代碼添加上,啓動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html

如上圖,可以看到暴漏出來的控制器信息,點擊進入可以看到詳細信息。

兩個注意點:

1.  paramType會直接影響程序的運行期,如果paramType與方法參數獲取使用的註解不一致,會直接影響到參數的接收。

例如:

使用Sawgger UI進行測試,接收不到!

2.  還有一個需要注意的地方:

Conntroller中定義的方法必須在@RequestMapper中顯示的指定RequestMethod類型,否則SawggerUi會默認爲全類型皆可訪問, API列表中會生成多條項目。

如上圖:updatePassword()未指定requestMethod,結果生成了7條API信息。所以如果沒有特殊需求,建議根據實際情況加上requestMethod。

 

5:Swagger UI面板說明

6:參考

http://blog.didispace.com/springbootswagger2/

http://blog.csdn.net/jia20003/article/details/50700736

Swagger官網 :http://swagger.io/

Spring Boot & Swagger UI : http://fruzenshtein.com/spring-boot-swagger-ui/

Github:https://github.com/swagger-api/swagger-core/wiki/Annotations

 

---------------------------------------------------------------------------------------

7:接收對象傳參的例子

在POJO上增加

  1. package com.zhongying.api.model.base;
  2. import io.swagger.annotations.ApiModel;
  3. import io.swagger.annotations.ApiModelProperty;
  4. /**
  5. * 醫生對象模型,不要使用該類
  6. * @author SUNF
  7. *
  8. */
  9. @ApiModel(value="醫生對象模型")
  10. public class DemoDoctor{
  11. @ApiModelProperty(value="id" ,required=true)
  12. private Integer id;
  13. @ApiModelProperty(value="醫生姓名" ,required=true)
  14. private String name;
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. @Override
  28. public String toString() {
  29. return "DemoDoctor [id=" + id + ", name=" + name + "]";
  30. }
  31. }

注意: 在後臺採用對象接收參數時,Swagger自帶的工具採用的是JSON傳參,    測試時需要在參數上加入@RequestBody,正常運行採用form或URL提交時候請刪除。 

  1. package com.zhongying.api.controller.app;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.servlet.http.HttpServletRequest;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestBody;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. import com.github.pagehelper.PageInfo;
  12. import com.zhongying.api.exception.HttpStatus401Exception;
  13. import com.zhongying.api.model.base.DemoDoctor;
  14. import io.swagger.annotations.Api;
  15. import io.swagger.annotations.ApiImplicitParam;
  16. import io.swagger.annotations.ApiImplicitParams;
  17. import io.swagger.annotations.ApiOperation;
  18. /**
  19. * 醫生類(模擬)
  20. * @author SUNF
  21. */
  22. @RequestMapping("/api/v1")
  23. @Controller
  24. @Api(value = "DoctorTestController-醫生信息接口模擬")
  25. public class DoctorTestController {
  26. /**
  27. * 添加醫生
  28. *
  29. * 在使用對象封裝參數進行傳參時,需要在該對象添加註解,將其註冊到swagger中
  30. * @link com.zhongying.api.model.base.DemoDoctor
  31. *
  32. * 注意: 在後臺採用對象接收參數時,Swagger自帶的工具採用的是JSON傳參,
  33. * 測試時需要在參數上加入@RequestBody,正常運行採用form或URL提交時候請刪除。
  34. *
  35. * @param doctor 醫生類對象
  36. * @return
  37. * @throws Exception
  38. */
  39. @ResponseBody
  40. @RequestMapping(value="/doctor", method= RequestMethod.POST )
  41. @ApiOperation(value="添加醫生信息", notes="")
  42. public String addDoctor(@RequestBody DemoDoctor doctor) throws Exception{
  43. if(null == doctor || doctor.getId() == null){
  44. throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知原因","請聯繫管理員");
  45. }
  46. try {
  47. System.out.println("成功----------->"+doctor.getName());
  48. } catch (Exception e) {
  49. throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知原因","請聯繫管理員");
  50. }
  51. return doctor.getId().toString();
  52. }
  53. /**
  54. * 刪除醫生
  55. * @param doctorId 醫生ID
  56. * @return
  57. */
  58. @ResponseBody
  59. @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.DELETE )
  60. @ApiOperation(value="刪除醫生信息", notes="")
  61. @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
  62. public String deleteDoctor(@RequestParam Integer doctorId){
  63. if(doctorId > 2){
  64. return "刪除失敗";
  65. }
  66. return "刪除成功";
  67. }
  68. /**
  69. * 修改醫生信息
  70. * @param doctorId 醫生ID
  71. * @param doctor 醫生信息
  72. * @return
  73. * @throws HttpStatus401Exception
  74. */
  75. @ResponseBody
  76. @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.POST )
  77. @ApiOperation(value="修改醫生信息", notes="")
  78. @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
  79. public String updateDoctor(@RequestParam Integer doctorId, @RequestBody DemoDoctor doctor) throws HttpStatus401Exception{
  80. if(null == doctorId || null == doctor){
  81. throw new HttpStatus401Exception("修改醫生信息失敗","DT3391","id不能爲空","請修改");
  82. }
  83. if(doctorId > 5 ){
  84. throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID");
  85. }
  86. System.out.println(doctorId);
  87. System.out.println(doctor);
  88. return "修改成功";
  89. }
  90. /**
  91. * 獲取醫生詳細信息
  92. * @param doctorId 醫生ID
  93. * @return
  94. * @throws HttpStatus401Exception
  95. */
  96. @ResponseBody
  97. @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.GET )
  98. @ApiOperation(value="獲取醫生詳細信息", notes="僅返回姓名..")
  99. @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
  100. public DemoDoctor getDoctorDetail(@RequestParam Integer doctorId) throws HttpStatus401Exception{
  101. System.out.println(doctorId);
  102. if(null == doctorId){
  103. throw new HttpStatus401Exception("查看醫生信息失敗","DT3390","未知原因","請聯繫管理員");
  104. }
  105. if(doctorId > 3){
  106. throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID");
  107. }
  108. DemoDoctor doctor = new DemoDoctor();
  109. doctor.setId(1);
  110. doctor.setName("測試員");
  111. return doctor;
  112. }
  113. /**
  114. * 獲取醫生列表
  115. * @param pageIndex 當前頁數
  116. * @param pageSize 每頁記錄數
  117. * @param request
  118. * @return
  119. * @throws HttpStatus401Exception
  120. */
  121. @ResponseBody
  122. @RequestMapping(value="/doctor", method= RequestMethod.GET )
  123. @ApiOperation(value="獲取醫生列表", notes="目前一次全部取,不分頁")
  124. @ApiImplicitParams({
  125. @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
  126. @ApiImplicitParam(paramType="query", name = "pageIndex", value = "當前頁數", required = false, dataType = "String"),
  127. @ApiImplicitParam(paramType="query", name = "pageSize", value = "每頁記錄數", required = true, dataType = "String"),
  128. })
  129. public PageInfo<DemoDoctor> getDoctorList(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
  130. @RequestParam(value = "pageSize", required = false) Integer pageSize,
  131. HttpServletRequest request) throws HttpStatus401Exception{
  132. String token = request.getHeader("token");
  133. if(null == token){
  134. throw new HttpStatus401Exception("沒有權限","SS8888","沒有權限","請查看操作文檔");
  135. }
  136. if(null == pageSize){
  137. throw new HttpStatus401Exception("每頁記錄數不粗安在","DT3399","不存在pageSize","請查看操作文檔");
  138. }
  139. DemoDoctor doctor1 = new DemoDoctor();
  140. doctor1.setId(1);
  141. doctor1.setName("測試員1");
  142. DemoDoctor doctor2 = new DemoDoctor();
  143. doctor2.setId(2);
  144. doctor2.setName("測試員2");
  145. List<DemoDoctor> doctorList = new ArrayList<DemoDoctor>();
  146. doctorList.add(doctor1);
  147. doctorList.add(doctor2);
  148. return new PageInfo<DemoDoctor>(doctorList);
  149. }
  150. }

增加header:

    現在很多請求需要在header增加額外參數,可以參考getDoctorList()的做法,使用request接收。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章