一、自動生成API工具
1、Swagger:是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。可以生成一個具有互動性的API控制檯,開發者可以用來快速學習和嘗試API。支持多種語言,如:Scala、Java、Ruby、PHP、JavaScript等;
2、i /o docs:一種Restful風格的交互式文檔系統;
3、Dexy:一款非常靈活的文檔工具;
4、自己編寫插件生成Api文檔。
二、在SpringBoot中使用Swagger
1、引入依賴
<!-- swagger -->
<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>
<!-- swagger -->
2、新建Swagger配置類
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.william.springboot.springbootshiro.controller"))//掃描的包名
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger生成api文檔")
.description("簡單優雅的restfun風格,自動生成api文檔")
.termsOfServiceUrl("http://localhost:8080/swagger-ui.html")
.version("1.0")
.build();
}
}
3、編寫接口入口
@Api(value="用戶相關接口API",tags="用戶接口")
@RestController
@RequestMapping("/user")
public class UserInfoController {
@ApiOperation(value = "查詢用戶根據ID", notes = "查詢用戶",produces = MediaType.APPLICATION_JSON_VALUE)
@ApiImplicitParam(name = "userid", value = "userid", required = true,paramType="path", dataType = "String")
@RequestMapping(value="/get/{userid}",method=RequestMethod.GET)
public String getUserById(@PathVariable("userid") String userid) {
System.out.println("-----"+userid);
/**
* dosomework
*/
System.out.println("---"+userid);
return "William";
}
@ApiOperation(value = "新增用戶", notes = "保存")
@ApiImplicitParam(name = "userInfo", value = "userInfo", required = true, dataType = "UserInfo")
@PostMapping("/save")
public String addUser(@RequestBody UserInfo userInfo) {
/**
* dosomework
*/
return "success";
}
}
4、訪問API自動文檔
地址:項目路徑/swagger-ui.html#/
至此,你的項目就成功集成了Swagger,大大方便了自己寫API文檔的勞動量,方便了前端調用接口聯調。