微服务【1.1】Swagger的使用
隨著前后端分離架構和微服務架構的流行,我們使用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。具體效果如下圖所示:
Swagger2的配置步驟如下:
一、引入依賴
pom.wml
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency>二、引入配置類(并在生產環境屏蔽swagger)
@Configuration @EnableSwagger2 public class SwaggerConfig{@AutowiredConfigService configService;@Beanpublic Docket customDocket() {//這里環境也可以根據拿到啟動參數進行判斷(生產環境屏蔽swagger)if(configService.getServerEnv() == ServerEnvEnum.ONLINE) {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfoOnline()).select().paths(PathSelectors.none())//如果是線上環境,添加路徑過濾,設置為全部都不符合.build();}else {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());}}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("XXX系統").description("XXX系統接口").license("").licenseUrl("").termsOfServiceUrl("").version("1.0.0").contact(new Contact("","", "")).build();}private ApiInfo apiInfoOnline() {return new ApiInfoBuilder().title("").description("").license("").licenseUrl("").termsOfServiceUrl("").version("").contact(new Contact("","", "")).build();} }啟動項目后打開
http://localhost:8080/v2/api-docs
能看到 json 格式的接口描述
http://localhost:8080/swagger-ui.html
查看 ui 界面
Spring Boot中使用Swagger2構建強大的RESTful API文檔
https://www.cnblogs.com/code-java/p/6419478.html
404
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Nov 24 19:57:13 CST 2016
There was an unexpected error (type=Not Found, status=404).
No message available
加上靜態文件映射配置
package io.github.talelin.latticy.config;import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");} }常用到的注解有:
- Api
- ApiModel
- ApiModelProperty
- ApiOperation
- ApiParam
- ApiResponse
- ApiResponses
- ResponseHeader
1. api標記
Api 用在類上,說明該類的作用。可以標記一個Controller類做為swagger 文檔資源,使用方式:
| value | url的路徑值 |
| tags | 如果設置這個值、value的值會被覆蓋 |
| description | 對api資源的描述 |
| basePath | 基本路徑可以不配置 |
| position | 如果配置多個Api 想改變顯示的順序位置 |
| produces | For example, "application/json, application/xml" |
| consumes | For example, "application/json, application/xml" |
| protocols | Possible values: http, https, ws, wss. |
| authorizations | 高級特性認證時配置 |
| hidden | 配置為true 將在文檔中隱藏 |
在SpringMvc中的配置如下:
@Controller @RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}) @Api(value = "/pet", description = "Operations about pets") public class PetController {}2. ApiOperation標記
ApiOperation:用在方法上,說明方法的作用,每一個url資源的定義,使用方式:
@ApiOperation(value = "Find purchase order by ID",notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",response = Order,tags = {"Pet Store"})與Controller中的方法并列使用。
屬性配置:
| value | url的路徑值 |
| tags | 如果設置這個值、value的值會被覆蓋 |
| description | 對api資源的描述 |
| basePath | 基本路徑可以不配置 |
| position | 如果配置多個Api 想改變顯示的順序位置 |
| produces | For example, "application/json, application/xml" |
| consumes | For example, "application/json, application/xml" |
| protocols | Possible values: http, https, ws, wss. |
| authorizations | 高級特性認證時配置 |
| hidden | 配置為true 將在文檔中隱藏 |
| response | 返回的對象 |
| responseContainer | 這些對象是有效的 "List", "Set" or "Map".,其他無效 |
| httpMethod | "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH" |
| code | http的狀態碼 默認 200 |
| extensions | 擴展屬性 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order/{orderId}", method = GET)@ApiOperation(value = "Find purchase order by ID",notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",response = Order.class,tags = { "Pet Store" })public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId)throws NotFoundException {Order order = storeData.get(Long.valueOf(orderId));if (null != order) {return ok(order);} else {throw new NotFoundException(404, "Order not found");}}3. ApiParam標記
ApiParam請求屬性,使用方式:
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)與Controller中的方法并列使用。
屬性配置:
| name | 屬性名稱 |
| value | 屬性值 |
| defaultValue | 默認屬性值 |
| allowableValues | 可以不配置 |
| required | 是否屬性必填 |
| access | 不過多描述 |
| allowMultiple | 默認為false |
| hidden | 隱藏該屬性 |
| example | 舉例子 |
在SpringMvc中的配置如下:
public ResponseEntity<Order> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)@PathVariable("orderId") String orderId)4. ApiResponse
ApiResponse:響應配置,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")與Controller中的方法并列使用。 屬性配置:
| code | http的狀態碼 |
| message | 描述 |
| response | 默認響應類 Void |
| reference | 參考ApiOperation中配置 |
| responseHeaders | 參考 ResponseHeader 屬性配置說明 |
| responseContainer | 參考ApiOperation中配置 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)@ApiOperation(value = "Place an order for a pet", response = Order.class)@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })public ResponseEntity<String> placeOrder(@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {storeData.add(order);return ok("");}5. ApiResponses
ApiResponses:響應集配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })與Controller中的方法并列使用。 屬性配置:
| value | 多個ApiResponse配置 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)@ApiOperation(value = "Place an order for a pet", response = Order.class)@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })public ResponseEntity<String> placeOrder(@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {storeData.add(order);return ok("");}6. ResponseHeader
響應頭設置,使用方法
@ResponseHeader(name="head1",description="response head conf")與Controller中的方法并列使用。 屬性配置:
| name | 響應頭名稱 |
| description | 頭描述 |
| response | 默認響應類 Void |
| responseContainer | 參考ApiOperation中配置 |
在SpringMvc中的配置如下:
@ApiModel(description = "群組")7. 其他
- @ApiImplicitParams:用在方法上包含一組參數說明;
- @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個請求參數的各個方面
- paramType:參數放在哪個地方
- name:參數代表的含義
- value:參數名稱
- dataType: 參數類型,有String/int,無用
- required : 是否必要
- defaultValue:參數的默認值
- @ApiResponses:用于表示一組響應;
- @ApiResponse:用在@ApiResponses中,一般用于表達一個錯誤的響應信息;
- code: 響應碼(int型),可自定義
- message:狀態碼對應的響應信息
- @ApiModel:描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam注解進行描述的時候;
- @ApiModelProperty:描述一個model的屬性。
這部分引用自:https://www.jianshu.com/p/12f4394462d5
@ApiIgnore屏蔽方法/參數/字段
@ApiIgnore 可用在方法上,類上,參數上
如果想在文檔中屏蔽掉刪除用戶的接口(user/delete),那么只需要在刪除用戶的方法上加上 @ApiIgnore 即可。
1、屏蔽 delete 方法
?2、屏蔽 pageable 參數
@ApiOperation(value = "查詢") @ApiImplicitParams({ @ApiImplicitParam(name = "page", value = "當前頁碼"),@ApiImplicitParam(name = "size", value = "每頁數據條數"), }) @GetMapping("/user/query") public APIResult<List<UserVO>> query(QueryVO queryVO, @ApiIgnore @PageableDefault Pageable pageable) {List<ArchiveVO> page = service.queryUser(queryVO, pageable);return RestOuts.ok(page); }導出 Swagger 文檔
前提是項目已經開啟了 swagger 依賴,能夠導出 json 格式的 swagger 數據。
開啟 swagger 后,?http://localhost:8080/v2/api-docs?就是 json 數據地址,或者如果有 swagger-ui 界面,在主頁左上角有此鏈接。
Swagger2Markup
Swagger2Markup 是 Github 上的一個開源項目。該項目主要用來將 Swagger 自動生成的文檔轉換成幾種流行的格式以便于靜態部署和使用,比如:AsciiDoc、Markdown、Confluence。
Swagger2Markup 項目是將 swagger 文檔導出為其他格式的基礎。
Swagger2Markup / swagger2markup
https://github.com/Swagger2Markup/swagger2markup
spring-swagger2markup-demo
我們將 swagger 導出為 pdf、html、markdown 格式都需要用到 Swagger2Markup 項目,但這個項目配置比較麻煩,所以官方給出了一個 demo 項目。
有了這個項目,我們只需要將自己的 swagger 數據保存為 json 文檔,然后填入這個項目的配置屬性,運行下 test 就好了。
Swagger2Markup / spring-swagger2markup-demo
https://github.com/Swagger2Markup/spring-swagger2markup-demo
導出為pdf或html
1 下載 Swagger2Markup / spring-swagger2markup-demo 項目,倒入為 maven 項目,等待 maven 下載依賴完成。
2 將自己的 swagger 數據保存為 api-docs.json
3 修改 spring-swagger2markup-demo 項目的 pom 文件,找到配置項?<swagger.input>,改為自己 json 文檔地址,絕對目錄或相對目錄都行。
4 執行?mvn test?命令,不報錯的話,在項目下的 target/asciidoc 目錄就能找到生成的文檔。
其實,這里的?mvn test?包含兩個步驟:
第一步將 json 轉為 ASCIIDOC 格式。
第二步,將 ASCIIDOC 轉為 pdf 和 html 格式。
使用中發現生成的 pdf 中有的中文字符不顯示,但 html 是好的,可以先瀏覽器打開 html,再打印為 pdf 即可。
導出swagger2生成的文檔
https://www.cnblogs.com/zeussbook/p/11091520.html
導出為markdown
默認情況下,Swagger2Markup 將 json 渲染為 asciidoc 基本文檔格式,然后再轉為 pdf 或 html 格式。
如果我們想轉換為 markdown 格式,只需要修改一個參數即可
修改 spring-swagger2markup-demo 項目的 pom 文件,找到?swagger2markup-maven-plugin?插件的配置項?<swagger2markup.markupLanguage>?默認是?ASCIIDOC?改為?MARKDOWN,然后執行 maven 插件的構建過程即可。
這次我們不需要執行?mvn test?只執行第一步即可。
Spring Boot 2.x基礎教程:Swagger靜態文檔的生成
https://aijishu.com/a/1060000000017742
Failed to execute goal ‘convertSwagger2markup’
首次執行時報這個錯,原因是 swagger2 導出的 json 文檔不規范,少了幾個必須的字段,導致 Swagger2Markup 執行失敗。
1 首先,可以用官方的 json 文檔試一下,如果沒問題,就說明 spring-swagger2markup-demo 項目配置是沒問題的。直接把數據粘貼百度的json規范的工具也可以。
官方json示例
https://petstore.swagger.io/v2/swagger.json
2 打開官方提供的一個 swagger 編輯器
https://editor.swagger.io/
把自己的 json 帖進去,右邊會告訴你格式不準確的地方。
如下圖,我這里生成的 json 就是缺了 title, version, license.name 屬性,導致無法生成文檔,加上就好了。
右邊下面還會提示好多編碼錯誤,不用管,只把缺字段的補上就好了。
Api2Doc
Swagger 比較臃腫,不太友好,偶然發現一個 Api2Doc 項目,和我們平常工作中用的 ShowDoc 文檔非常相似,簡潔又清晰。
terran4j/commons
https://github.com/terran4j/commons/tree/master/commons-api2doc
還在用 Swagger2 生成 Restful API 文檔?來試試 Api2Doc 吧
https://my.oschina.net/u/3017144/blog/1679922
用Api2Doc代替Swagger2生成 Restful API 文檔
https://www.jianshu.com/p/281df3ecd3b0
參考搬運:http://www.madaimeng.com/article/Swagger/
總結
以上是生活随笔為你收集整理的微服务【1.1】Swagger的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ElasticSearch和mongod
- 下一篇: PostgreSQL 9.6.0 手册