整合swagger2生成Restful Api接口文档
整合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源碼
相關文章導讀
?
https://www.imooc.com/article/20521
?webapi文檔描述-swagger
https://www.codercto.com/a/23839.html
http://blog.didispace.com/spring-boot-starter-swagger-1.2.0/
慕課手記:
http://www.imooc.com/article/15384
?
轉載于:https://www.cnblogs.com/gaogaoyanjiu/p/9662018.html
總結
以上是生活随笔為你收集整理的整合swagger2生成Restful Api接口文档的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数组的解构赋值(未完成)
- 下一篇: KMP经典算法与变形的应用(字符串par