您的位置:首页 > 编程语言 > Java开发

使用Spring Boot&Swagger快速构建REST API并生成优美的API文档

2017-08-10 16:46 1801 查看

使用Spring Boot&Swagger快速构建REST API并生成优美的API文档

通常我们要构建API 服务,自然少不了文档,但由于API与文档的分离使得我们每次对API进行的更改都需要去同步文档,稍有纰漏难免就会出现调用的异常,而编写、同步文档通常是比较繁琐无趣的事。现在得益于Spring BootSwagger,我们不但可以极速的搭建REST、RESTful风格的API服务并且还可以生成优美、强大的在线或离线API文档。

引入Maven依赖

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
</dependencies>


创建Application主类

package example;//注意包结构
@SpringBootApplication
public class Application {

public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}


创建Swagger配置类

package example.config;//注意包结构
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInf())
.select()
.apis(RequestHandlerSelectors.basePackage("example.web.controller"))//要扫描的API(Controller)基础包
.paths(PathSelectors.any())
.build();
}
private ApiInfo buildApiInf() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2 UI构建API文档")
.contact("土豆")
.version("1.0")
.build();
}
}


创建RestController 构建一个简单计算服务API

package example.web.controller;//注意包结构
@Api(value = "计算服务",description="简单的计算服务,提供加减乘除运算API")
@RestController
@RequestMapping("/compute")
public class ComputeController {
@ApiOperation("加法运算")
@PostMapping("/add")
public Double add(@RequestParam Double a,  @RequestParam Double b) {
return a + b;
}

@ApiOperation("减法运算")
@PostMapping("/sub")
public Double sub(@RequestParam Double a,  @RequestParam Double b) {
return a - b;
}

@ApiOperation("乘法运算")
@PostMapping("/mul")
public Double mul(@RequestParam Double a,  @RequestParam Double b) {
return a * b;
}

@ApiOperation("除法运算")
@PostMapping("/div")
public Double div(@ApiParam("被除数")@RequestParam Double a, @ApiParam("除数")@RequestParam   Double b) {
return a / b;
}
}

@Api
注解用来表述该服务的信息,如果不使用则显示类名称.
@ApiOperation
注解用于表述接口信息
@ApiParam
注解用于描述接口的参数

通过上面几步我们已经成功构建了一个具备加减乘除的计算服务API,并且已经拥有一份不错的在线文档了,现在我们来启动它,执行
mvn spring-boot:run
,或直接运行
Application.main()


启动成功后,访问http://localhost:8080/swagger-ui.html,便可以看到我们刚才构建的计算服务的API文档了。



swagger-ui

Swagger UI不仅仅是文档,还提供了在线API调试的功能,我们可以调试下我们的除法运算API。



swagger-ui

点击Try it out!后可以看到我们成功的调用了除法运算API并获得了正确的响应。



swagger-ui

创建RESTful 风格的API及文档

下面我们以用户的增删改查服务为例

1.创建Model

package example.model;//注意包结构
public class User {

private Long id;
private String username;
private Integer age;

//省略getter、setter方法

}

2.创建RestController

package example.web.controller;//注意包结构
@RestController
@RequestMapping("/user")
@Api(value = "用户服务",description = "提供RESTful风格API的用户的增删改查服务")
public class UserController {
//模拟DAO层
private final Map<Long, User> repository = new HashMap<Long, User>();

@PostMapping
@ApiOperation("添加用户")
public Boolean add(@RequestBody User user) {
repository.put(user.getId(), user);
return true;
}

@DeleteMapping("/{id}")
@ApiOperation("通过ID删除用户")
public Boolean delete(@PathVariable Long id) {
repository.remove(id);
return true;
}

@PutMapping
@ApiOperation("更新用户")
public Boolean update(@RequestBody User user) {
repository.put(user.getId(), user);
return true;
}

@GetMapping("/{id}")
@ApiOperation("通过ID查询用户")
public User findById(@PathVariable Long id) {
return repository.get(id);
}
}

这里说点题外话,
@GetMapping,@PostMapping,@PutMapping,@DeleteMapping
等注解是
Spring MVC 4.3X
版本添加的新注解,它们是对
@RequestMapping
注解的简化封装。

好了,我们重新启动下Application,再次访问http://localhost:8080/swagger-ui.html,用户服务的RESTful API文档也已生成。



swagger-ui

我们来尝试调用添加用户API增加一位用户



swagger-ui

成功后,我们调用查询API,来进行查询看时候可以返回正确的JSON数据。



swagger-ui

为Model(JSON)添加注释

为了使API的调用者能够清晰的知道请求和响应的Model中各字段的具体含义,我们需要对其添加一些简单的注释,而Swagger也为我们提供了相应的注解比如@ApiModel、@ApiModelProperty来帮助我们解释我们的Model,下面就是最简单的使用例子,详细用法及更多相关注解点我查看~

@ApiModel("User(用户模型)")
public class User {
@ApiModelProperty("ID")
private Long id;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("年龄")
private Integer age;

//省略getter、setter方法
}




swagger-ui

这一切是不是很简单?从开发API到构建高逼格的API文档完全可以用极速来形容。当然,本文也只是展现了Spring Boot + Swagger的冰山一角,要了解更多细节那就快去翻阅官方文档吧~

本示例完整代码的GIT地址点击我~

Swagger-Core文档点击我~

SpringFox文档点击我~

Spring Boot 文档点击我~

还不错的Spring Boot系列教程点击我~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: