一、 作用:
1. 接口的文檔在線自動生成。
2. 接口測試。
二、模塊介紹
Swagger是一組開源項目,其中主要要項目及功能如下:
1、Swagger Codegen: 通過Codegen 可以將描述文件生成html格式和cwiki形式的接口文檔,同時也能生成多鍾語言的服務端和客戶端的代碼。支持通過jar包,docker,node等方式在本地化執行生成。也可以在后面的Swagger Editor中在線生成。
2、Swagger UI:提供了一個可視化的UI頁面展示描述文件。接口的調用方、測試、項目經理等都可以在該頁面中對相關接口進行查閱和做一些簡單的接口請求。該項目支持在線導入描述文件和本地部署UI項目。
3、Swagger Editor: 類似於markendown編輯器的編輯Swagger描述文件的編輯器,該編輯支持實時預覽描述文件的更新效果。也提供了在線編輯器和本地部署編輯器兩種方式。
4、Swagger Inspector: 感覺和postman差不多,是一個可以對接口進行測試的在線版的postman。比在Swagger UI里面做接口請求,會返回更多的信息,也會保存你請求的實際請求參數等數據。
5、Swagger Hub:集成了上面所有項目的各個功能,你可以以項目和版本為單位,將你的描述文件上傳到Swagger Hub中。在Swagger Hub中可以完成上面項目的所有工作,需要注冊賬號,分免費版和收費版。
PS:
Springfox Swagger: Spring 基於swagger規范,可以將基於SpringMVC和Spring Boot項目的項目代碼,自動生成JSON格式的描述文件。本身不是屬於Swagger官網提供的,在這里列出來做個說明,方便后面作一個使用的展開。
三、配置
1、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>
2、創建swagger配置類(在Application.java同級創建Swagger2的配置類Swagger2)
package com.example.demo;
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;
@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.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 創建該API的基本信息(這些基本信息會展現在文檔頁面中)
* 訪問地址:http://項目實際地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("朦朧的夜測試Swagger項目")
.description("更多請關注 博客園--朦朧的夜")
.termsOfServiceUrl("https://www.cnblogs.com/liconglong/")
.contact("lcl")
.version("1.0")
.build();
}
}
如上代碼所示,通過createRestApi函數創建Docket的Bean之后,apiInfo()用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。
注意:一定要加上@Configuration和@EnableSwagger2這兩個注解,@EnableSwagger2應該是標注該類是Swagger的配置類,@Configuration可以使spring啟動就加載該類,如果這兩個配置文件不加,則項目啟動后,打開Swagger頁面后,內容為空。
3、添加文檔內容(在完成了上述配置后,其實已經可以生產文檔內容,但是這樣的文檔主要針對請求本身,描述的主要來源是函數的命名,對用戶並不友好,我們通常需要自己增加一些說明來豐富文檔內容)
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.example.demo.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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;
@Controller
@RequestMapping("/menglongdeyeController")
@Api(value = "朦朧的夜的測試接口")
public class SwaggerTestController {
@ResponseBody
@RequestMapping(value ="/test1", method= RequestMethod.GET)
@ApiOperation(value="單獨一個入參測試接口", notes="接口描述,例如:只能輸入‘朦朧的夜’")
@ApiImplicitParam(paramType="query", name = "blogName", value = "博客名稱", required = true, dataType = "String",defaultValue = "朦朧的夜")
public String test1(@RequestParam String blogName){
if("朦朧的夜".equals(blogName)){
return "對了!!!";
}else{
return "錯了!!!";
}
}
@ResponseBody
@RequestMapping("/test2")
@ApiOperation(value="多個入參測試接口", notes="輸入用戶名密碼")
@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 test2(@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.htm
說明:controller一定要加請求類型(post、get等),如果不添加,則會生成7個接口(例如Test2接口),即每個請求類型產生一個接口。
點擊接口名稱,可進行接口調用測試
輸入參數后,點擊 Try it out!進行測試,測試結果如下,可查看接口調用狀態,如果狀態為200(成功),則有相應的返回值等信息。
如上圖,可以看到暴漏出來的控制器信息,點擊進入可以看到詳細信息。
特殊說明一下請求參數為對象時,在POJO上增加@ApiModel(value="學生對象模型")
@ApiModel(value="學生對象模型")
public class Student {
private String name;
private String age;
private String classes;
}
Controller中代碼如下:
@ResponseBody
@RequestMapping(value="/student", method= RequestMethod.POST )
@ApiOperation(value="添加學生信息", notes="")
public Student addDoctor(@RequestBody List<Student> studentList) throws Exception{
if(studentList == null || studentList.size() == 0){
throw new Exception("學生集合不允許為空!");
}
for (Student student : studentList){
if(StringUtils.isEmpty(student.getName())){
throw new Exception("名字不允許為空!");
}
}
return studentList.get(0);
}
使用:
調用:
五、導出接口文檔
1、配置
pom文件配置插件
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<!-- api-docs訪問url -->
<swaggerInput>http://localhost:8080/v2/api-docs</swaggerInput>
<!-- 生成為單個文檔,輸出路徑
<outputFile>src/main/doc/ml</outputFile>-->
<!-- 生成為多個文檔,輸出路徑 -->
<outputDir>src/main/doc/ml</outputDir>
<config>
<!-- wiki格式文檔 -->
<!--<swagger2markup.markupLanguage>CONFLUENCE_MARKUP</swagger2markup.markupLanguage> -->
<!-- ascii格式文檔 -->
<swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
<!-- markdown格式文檔 -->
<!--<swagger2markup.markupLanguage>MARKDOWN</swagger2markup.markupLanguage>-->
<swagger2markup.pathsGroupedBy>TAGS</swagger2markup.pathsGroupedBy>
</config>
</configuration>
</plugin>
配置文件說明
configuration.swaggerInput :該標簽內容需修改為需要導出接口項目的/v2/api-docs 路徑
configuration.outputFile :該標簽為生成單個文檔指定文檔生成路徑,如生成txt、md等文件,可隨意修改;但注意,該標簽與outputDir標簽二選一;
configuration.outputDir :該標簽為生成多個文檔指定文檔目錄,如生成ASCIIDOC文件,該類文件可用於結合asciidoctor插件生成html文件;
configuration.config :該標簽內定義的swagger2markup.markupLanguage子標簽,只能同時存在一個,如指定生成markdown 即md文件時,就不能指定生成其他類型;
注意:指定生成ASCIIDOC文件類型時,需與configuration.outputDir標簽配合使用;
2、運行插件(雙擊運行,即可生成左側目錄中的接口規范文檔)
-----------------------------------------------------
后續使用問題及解決:
1、使用插件生成離線文檔時,提示 swaggerInput 指定的文件找不到
解決:(1)生成離線文檔時,項目必須處於啟動狀態,否則不能生成
(2)swaggerInput 指定的地址有可能不太一樣,需要調整,具體以swagger頁面的地址為准,以下圖所示: