整合swagger2生成Restful Api介面文件 webapi文件描述-swagger
整合swagger2生成Restful Api介面文件
swagger Restful文件生成工具 2017-9-30
官方地址:https://swagger.io/docs/specification/about/
官方Github:https://github.com/swagger-api/swagger-core/wiki/Annotations
啟動專案,訪問http://localhost:8082/swagger-ui.html檢視API
注意,此專案示例中,使用了三種ui依賴,每種依賴對應的訪問頁面不同:
springfox-swagger-ui -> http://localhost:8082/swagger-ui.html
swagger-bootstrap-ui -> http://localhost:8082/doc.html
swagger-ui-layer -> http://localhost:8082/docs.html
使用方法:
1.新增依賴(springfox-swagger2依賴是必須的,三種ui依賴只需要使用一個就行)
<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.建立配置檔案Swagger2Config.java
@EnableSwagger2
@Configuration
public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //為當前包路徑 .apis(RequestHandlerSelectors.basePackage("com.zyd.controller")) .paths(PathSelectors.any()) .build(); } //構建 api文件的詳細資訊函式 private ApiInfo apiInfo() { return new ApiInfoBuilder() //頁面標題 .title("Spring Boot 測試使用 Swagger2 構建RESTful API") .termsOfServiceUrl("http://localhost/") //建立人 .contact("zhyd") //版本號 .version("1.0") //描述 .description("API 描述") .build(); } }
注:@EnableSwagger2
註解一定不要漏掉
3.編寫文件
@RestController
@RequestMapping("/demo") @Api(value = "測試Swagger2",description="簡單的API") public class UserController { @ApiOperation(value = "建立使用者", notes = "根據User物件建立使用者") @ApiImplicitParams({ @ApiImplicitParam(dataType = "java.lang.Long", name = "id", value = "id", required = true, paramType = "path"), @ApiImplicitParam(dataType = "User", name = "user", value = "使用者資訊", required = true) }) @ApiResponses({ @ApiResponse(code = 500, message = "介面異常"), }) @RequestMapping(value = "/user/{id}", method = RequestMethod.POST) public User insert(@PathVariable Long id, @RequestBody User user) { System.out.println("id:" + id + ", user:" + user); user.setId(id); return user; } }
注意:如果api文件只是針對開發人員使用的,就需要後臺對v2/api-docs路徑進行過濾,對非開發人員應該是不可見的。
自定義api頁面
本例是使用的swagger-ui-layer主題(連結請見本文最後)。使用自定義api頁面就不需要在pom中配置ui依賴了,詳情檢視static目錄
api頁面訪問地址:http://localhost:8082/api.html
頁面效果參考
swagger-ui.html
bootstrap-ui.html
layer-ui.html.html
layer-ui-custom.html
參考連結
swagger-ui-layer地址:https://github.com/caspar-chen/swagger-ui-layer
Swagger-Bootstrap-UI地址:https://github.com/xiaoymin/Swagger-Bootstrap-UI
有問題歡迎留言(可能回覆有延遲,見諒)。
其他
原始碼請移步:Github原始碼
相關文章導讀
- SpringBoot專案實戰(8):四種讀取properties檔案的方式
- SpringBoot專案實戰(7):自定義異常處理介面
- SpringBoot專案實戰(6):開啟定時任務
- SpringBoot專案實戰(5):整合分頁外掛
- SpringBoot專案實戰(4):整合Mybatis
- SpringBoot專案實戰(3):整合Freemark模板
- SpringBoot專案實戰(2):整合SpringBoot
- SpringBoot專案實戰(1):新建Maven專案
https://www.imooc.com/article/20521
https://www.codercto.com/a/23839.html
http://blog.didispace.com/spring-boot-starter-swagger-1.2.0/
慕課手記:
http://www.imooc.com/article/15384