swagger管理RESTful API
swagger ui是一个API在线文档生成和测试的利器,我们既可以用它来作为API的文档,也可以用来测试API。
一、spring-boot集成
1.1 maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spi</artifactId>
<version>2.4.0</version>
</dependency>
1.2 编写配置类
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.erdaoya"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(" RESTful API ")
.description("详细文档请看wiki")
.contact("erdaoya")
.version("1.0")
.build();
}
}
1.3 注解实现Swagger
@RestController
@RequestMapping("/user/user")
public class UserResource {
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(method=RequestMethod.POST)
public String doPost(@RequestBody User user) {
return "success";
}
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(method=RequestMethod.GET)
public User doGet(Long id) {
return new User(id,"erdaoya","lps");
}
@ApiOperation(value="更新用户信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "User")
})
@RequestMapping(method=RequestMethod.PUT)
public String doPut(Long id, @RequestBody User user) {
return "success";
}
@ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping( method=RequestMethod.DELETE)
public String doDelete(Long id) {
return "success";
}
}
1.4 访问UI
浏览器访问:http://localhost:8081/swagger-ui.html#/
展开
输入参数,点击try it out调试
二、不依赖代码
2.1 下载swagger-ui:
git clone https://github.com/swagger-api/swagger-ui.git
2.2 编译,部署到nginx
2.3 编写yml 或者json文档
http://editor.swagger.io/
编写完文档后,复制到之前部署的swagger-ui目录下。修改indexh.tml指向json文件,再访问swagger-ui: