Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,容許API來始終保持同步。html
做用:java
1. 接口的文檔在線自動生成。node
2. 功能測試。git
Swagger是一組開源項目,其中主要要項目以下:github
1. Swagger-tools:提供各類與Swagger進行集成和交互的工具。例如模式檢驗、Swagger 1.2文檔轉換成Swagger 2.0文檔等功能。web
2. Swagger-core: 用於Java/Scala的的Swagger實現。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進行集成。spring
3. Swagger-js: 用於JavaScript的Swagger實現。express
4. Swagger-node-express: Swagger模塊,用於node.js的Express web應用框架。api
5. Swagger-ui:一個無依賴的HTML、JS和CSS集合,能夠爲Swagger兼容API動態生成優雅文檔。springboot
6. Swagger-codegen:一個模板驅動引擎,經過分析用戶Swagger資源聲明以各類語言生成客戶端代碼。
版本號請根據實際狀況自行更改。
<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>
在Application.java同級建立Swagger2的配置類Swagger2
package com.swaggerTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Swagger2配置類 * 在與spring boot集成時,放在與Application.java同級的目錄下。 * 經過@Configuration註解,讓Spring來加載該類配置。 * 再經過@EnableSwagger2註解來啓用Swagger2。 */ @Configuration @EnableSwagger2 public class Swagger2 { /** * 建立API應用 * apiInfo() 增長API相關信息 * 經過select()函數返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展示, * 本例採用指定掃描的包路徑來定義指定要創建API的目錄。 * * @return */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller")) .paths(PathSelectors.any()) .build(); } /** * 建立該API的基本信息(這些基本信息會展示在文檔頁面中) * 訪問地址:http://項目實際地址/swagger-ui.html * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構建RESTful APIs") .description("更多請關注http://www.baidu.com") .termsOfServiceUrl("http://www.baidu.com") .contact("sunf") .version("1.0") .build(); } }
如上代碼所示,經過createRestApi函數建立Docket的Bean以後,apiInfo()用來建立該Api的基本信息(這些基本信息會展示在文檔頁面中)。
在完成了上述配置後,其實已經能夠生產文檔內容,可是這樣的文檔主要針對請求自己,描述的主要來源是函數的命名,對用戶並不友好,咱們一般須要本身增長一些說明來豐富文檔內容。
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獲取 query:請求參數放置於請求地址,使用@RequestParam獲取 path:(用於restful接口)-->請求參數的獲取:@PathVariable body:(不經常使用) form(不經常使用) |
name:參數名 |
|
dataType:參數類型 |
|
required:參數是否必須傳 |
true | false |
value:說明參數的意思 |
|
defaultValue:參數的默認值 |
|
例子:
package com.swaggerTest.controller; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; /** * 一個用來測試swagger註解的控制器 * 注意@ApiImplicitParam的使用會影響程序運行,若是使用不當可能形成控制器收不到消息 * * @author SUNF */ @Controller @RequestMapping("/say") @Api(value = "SayController|一個用來測試swagger註解的控制器") public class SayController { @ResponseBody @RequestMapping(value ="/getUserName", method= RequestMethod.GET) @ApiOperation(value="根據用戶編號獲取用戶姓名", notes="test: 僅1和2有正確返回") @ApiImplicitParam(paramType="query", name = "userNumber", value = "用戶編號", required = true, dataType = "Integer") public String getUserName(@RequestParam Integer userNumber){ if(userNumber == 1){ return "張三丰"; } else if(userNumber == 2){ return "慕容復"; } else{ return "未知"; } } @ResponseBody @RequestMapping("/updatePassword") @ApiOperation(value="修改用戶密碼", notes="根據用戶id修改密碼") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name = "userId", value = "用戶ID", required = true, dataType = "Integer"), @ApiImplicitParam(paramType="query", name = "password", value = "舊密碼", required = true, dataType = "String"), @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密碼", required = true, dataType = "String") }) public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password, @RequestParam(value="newPassword") String newPassword){ if(userId <= 0 || userId > 2){ return "未知的用戶"; } if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){ return "密碼不能爲空"; } if(password.equals(newPassword)){ return "新舊密碼不能相同"; } return "密碼修改爲功!"; } }
完成上述代碼添加上,啓動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html
如上圖,能夠看到暴漏出來的控制器信息,點擊進入能夠看到詳細信息。
兩個注意點:
1. paramType會直接影響程序的運行期,若是paramType與方法參數獲取使用的註解不一致,會直接影響到參數的接收。
例如:
使用Sawgger UI進行測試,接收不到!
2. 還有一個須要注意的地方:
Conntroller中定義的方法必須在@RequestMapper中顯示的指定RequestMethod類型,不然SawggerUi會默認爲全類型皆可訪問, API列表中會生成多條項目。
如上圖:updatePassword()未指定requestMethod,結果生成了7條API信息。因此若是沒有特殊需求,建議根據實際狀況加上requestMethod。
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
---------------------------------------------------------------------------------------
在POJO上增長
package com.zhongying.api.model.base; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * 醫生對象模型,不要使用該類 * @author SUNF * */ @ApiModel(value="醫生對象模型") public class DemoDoctor{ @ApiModelProperty(value="id" ,required=true) private Integer id; @ApiModelProperty(value="醫生姓名" ,required=true) private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "DemoDoctor [id=" + id + ", name=" + name + "]"; } }
注意: 在後臺採用對象接收參數時,Swagger自帶的工具採用的是JSON傳參, 測試時須要在參數上加入@RequestBody,正常運行採用form或URL提交時候請刪除。
package com.zhongying.api.controller.app; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.zhongying.api.exception.HttpStatus401Exception; import com.zhongying.api.model.base.DemoDoctor; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; /** * 醫生類(模擬) * @author SUNF */ @RequestMapping("/api/v1") @Controller @Api(value = "DoctorTestController-醫生信息接口模擬") public class DoctorTestController { /** * 添加醫生 * * 在使用對象封裝參數進行傳參時,須要在該對象添加註解,將其註冊到swagger中 * @link com.zhongying.api.model.base.DemoDoctor * * 注意: 在後臺採用對象接收參數時,Swagger自帶的工具採用的是JSON傳參, * 測試時須要在參數上加入@RequestBody,正常運行採用form或URL提交時候請刪除。 * * @param doctor 醫生類對象 * @return * @throws Exception */ @ResponseBody @RequestMapping(value="/doctor", method= RequestMethod.POST ) @ApiOperation(value="添加醫生信息", notes="") public String addDoctor(@RequestBody DemoDoctor doctor) throws Exception{ if(null == doctor || doctor.getId() == null){ throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知緣由","請聯繫管理員"); } try { System.out.println("成功----------->"+doctor.getName()); } catch (Exception e) { throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知緣由","請聯繫管理員"); } return doctor.getId().toString(); } /** * 刪除醫生 * @param doctorId 醫生ID * @return */ @ResponseBody @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.DELETE ) @ApiOperation(value="刪除醫生信息", notes="") @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer") public String deleteDoctor(@RequestParam Integer doctorId){ if(doctorId > 2){ return "刪除失敗"; } return "刪除成功"; } /** * 修改醫生信息 * @param doctorId 醫生ID * @param doctor 醫生信息 * @return * @throws HttpStatus401Exception */ @ResponseBody @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.POST ) @ApiOperation(value="修改醫生信息", notes="") @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer") public String updateDoctor(@RequestParam Integer doctorId, @RequestBody DemoDoctor doctor) throws HttpStatus401Exception{ if(null == doctorId || null == doctor){ throw new HttpStatus401Exception("修改醫生信息失敗","DT3391","id不能爲空","請修改"); } if(doctorId > 5 ){ throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID"); } System.out.println(doctorId); System.out.println(doctor); return "修改爲功"; } /** * 獲取醫生詳細信息 * @param doctorId 醫生ID * @return * @throws HttpStatus401Exception */ @ResponseBody @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.GET ) @ApiOperation(value="獲取醫生詳細信息", notes="僅返回姓名..") @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer") public DemoDoctor getDoctorDetail(@RequestParam Integer doctorId) throws HttpStatus401Exception{ System.out.println(doctorId); if(null == doctorId){ throw new HttpStatus401Exception("查看醫生信息失敗","DT3390","未知緣由","請聯繫管理員"); } if(doctorId > 3){ throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID"); } DemoDoctor doctor = new DemoDoctor(); doctor.setId(1); doctor.setName("測試員"); return doctor; } /** * 獲取醫生列表 * @param pageIndex 當前頁數 * @param pageSize 每頁記錄數 * @param request * @return * @throws HttpStatus401Exception */ @ResponseBody @RequestMapping(value="/doctor", method= RequestMethod.GET ) @ApiOperation(value="獲取醫生列表", notes="目前一次所有取,不分頁") @ApiImplicitParams({ @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"), @ApiImplicitParam(paramType="query", name = "pageIndex", value = "當前頁數", required = false, dataType = "String"), @ApiImplicitParam(paramType="query", name = "pageSize", value = "每頁記錄數", required = true, dataType = "String"), }) public PageInfo<DemoDoctor> getDoctorList(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex, @RequestParam(value = "pageSize", required = false) Integer pageSize, HttpServletRequest request) throws HttpStatus401Exception{ String token = request.getHeader("token"); if(null == token){ throw new HttpStatus401Exception("沒有權限","SS8888","沒有權限","請查看操做文檔"); } if(null == pageSize){ throw new HttpStatus401Exception("每頁記錄數不粗安在","DT3399","不存在pageSize","請查看操做文檔"); } DemoDoctor doctor1 = new DemoDoctor(); doctor1.setId(1); doctor1.setName("測試員1"); DemoDoctor doctor2 = new DemoDoctor(); doctor2.setId(2); doctor2.setName("測試員2"); List<DemoDoctor> doctorList = new ArrayList<DemoDoctor>(); doctorList.add(doctor1); doctorList.add(doctor2); return new PageInfo<DemoDoctor>(doctorList); } }
增長header:
如今不少請求須要在header增長額外參數,能夠參考getDoctorList()的作法,使用request接收。