Spring-boot 之 Swagger2(打造不一樣的api)
一、Swagger2是什麽?
Swagger 是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件。
Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。
官網:http://swagger.io/
GitHub地址:https://github.com/swagger-api/swagger-ui
二、Swagger2的maven依賴
1 <dependency> 2 <groupId>io.springfox</groupId> 3 <artifactId>springfox-swagger2</artifactId> 4 <version>2.7.0</version> 5 </dependency> 6 <dependency> 7 <groupId>io.springfox</groupId> 8 <artifactId>springfox-swagger-ui</artifactId> 9 <version>2.7.0</version> 10 </dependency>
三、SwaggerConfig的配置
import org.springframework.beans.factory.annotation.Value; 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 Swagger2Configuration { @Value(value = "${swagger.package}") private String swaggerPackage; @Bean public Docket buildDocket() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInf()).select() .apis(RequestHandlerSelectors.basePackage(swaggerPackage))
.select()
.paths(PathSelectors.any()).build(); } @SuppressWarnings("deprecation") private ApiInfo buildApiInfo() { return new ApiInfoBuilder() .title("隨便找的個網站平臺API接口說明文檔") .description("百度一下:https://www.baidu.com/") .termsOfServiceUrl("https://www.baidu.com/") .version("1.0") .build(); } }
通過@Configuration
註解,讓Spring-boot來加載該類配置。再通過@EnableSwagger2
註解來啟用Swagger2Configuration。
再通過buildDocket函數創建Docket的Bean之後,
buildApiInfo()用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。
select() 函數返回一個 ApiSelectorBuilder 實例用來控制哪些接口暴露給Swagger2來展現。
一般采用指定掃描的包路徑來定義
Swagger會掃描該包下所有Controller定義的API,並產生文檔內容(除了被@ApiIgnore指定的請求)。
四、配置Controller中的API
下面的內容是基於spring-boot進行配置的,不一定適合所有框架(自己也是瞎琢磨出來的,有錯的地方歡迎指出)
1.這裏面有幾個常用到的註解
@Api:用在類上,說明該類的作用
@ApiOperation:用在方法上,說明方法的作用,標註在具體請求上,value和notes的作用差不多,都是對請求進行說明;tags則是對請求進行分類的,比如你有好幾個controller,分別屬於不同的功能模塊,那這裏我們就可以使用tags來區分了,看上去很有條理
@ApiImplicitParams:用在方法上包含一組參數說明
@ApiImplicitParam:[email protected],指定一個請求參數的各個方面
paramType:參數放在哪個地方
header 請求參數的獲取:@RequestHeader
query 請求參數的獲取:@RequestParam
path(用於restful接口) 請求參數的獲取:@PathVariable
body(不常用)
form(不常用)
name:參數名
dataType:參數類型
required:參數是否必須傳
value:參數的意思
defaultValue:參數的默認值
@ApiResponses:用於表示一組響應
@ApiResponse:[email protected],一般用於表達一個錯誤的響應信息
code:數字,例如400
message:信息,例如"請求參數沒填好"
response:拋出異常的類
@ApiModel:描述一個Model的信息(這種一般用在post創建的時候,[email protected],[email protected]候)表明這是一個被swagger框架管理的model,用於class上
@ApiModelProperty 這裏顧名思義,描述一個model的屬性,[email protected],這裏的value是對字段的描述,example是取值例子,註意這裏的example很有用,對於前後端開發工程師理解文檔起到了關鍵的作用,因為會在api文檔頁面上顯示出這些取值來;這個註解還有一些字段取值,可以自己研究,舉例說一個:position,表明字段在model中的順序
2.Controller中的實現
import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.share.service.BlogService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; @Api(value="博客相關接口") @RestController @RequestMapping("/blog") public class BlogController { @Autowired private BlogService blogService; @ResponseBody @ApiOperation(value ="查詢文章列表", notes="") @RequestMapping(value = "/getBlogList",method={RequestMethod.POST,RequestMethod.GET}) @ApiImplicitParam(paramType="query", name = "type_id", value = "類型ID", required = true, dataType = "String")public List<Map> getBlogList(HttpServletRequest req) { String type_id = req.getParameter("type_id");return blogService.getBlogList(type_id); }; }
備註:帶綠色背景的表示使用Swagger2的過程中,所用到的相關代碼
這個時候打開:http://localhost:8081/apidoc/index.html,你就可以看到
這個錯誤的原因是$ref需要一個JSON字符串,我們的類型不符合Swagger2的要求導致報錯,但如果繼續往滾動,是可以看到我們定義的接口的
並且這個接口是能夠請求到數據的,所以上面的錯誤我們可以忽略
額,但是作為有強迫癥的你,怎麽可能忽略,大多程序員都是眼睛進不了沙子的,更別說這麽大一粒沙子!!!
下一步就解決這個問題。
五、處理 Errors: responses.200.schema.items.$ref
上一步有說過是$ref需要一個JSON字符串,我們的類型不符合Swagger2的要求導致報錯。
找到原因就好辦了,只要我們把結果轉換成JSON字符串就好了。
1.在pom.xml裏面增加一項配置
<!-- FastJson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency>
2.將List<Map>轉為JSON
import com.alibaba.fastjson.JSON;
...
@ResponseBody @ApiOperation(value ="查詢博客列表", notes="根據url的id來指定刪除對象") @RequestMapping(value = "/getBlogList",method={RequestMethod.POST,RequestMethod.GET}) @ApiImplicitParam(paramType="query", name = "type_id", value = "類型ID", required = true, dataType = "String") public String getBlogList(HttpServletRequest req) { String type_id = req.getParameter("type_id"); List<Map> result = blogService.getBlogList(type_id); return JSON.toJSONString(result); }
備註:藍色背景的表示新增加的內容,接下來刷新接口就發現錯誤沒啦,問題解決了,好了,打完了!
Spring-boot 之 Swagger2(打造不一樣的api)