美文网首页
使用Swagger编写规范API接口

使用Swagger编写规范API接口

作者: 徒阿彬 | 来源:发表于2018-11-23 11:28 被阅读0次

Swagger的基本使用

概述

Swagger是一个流行的API开发框架,整合了RESTful风格与SpringMVC的特点。这个框架以“开放API声明”(OpenAPI Specification,OAS)为基础,对整个API的开发周期都提供了相应的解决方案,是一个非常庞大的项目(包括设计、编码和测试,几乎支持所有语言)。

swagger01.png

使用方法

    1. 在mavem项目环境中注入以下jar包
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
    1. 在现有springmvc的Controller请求上注入
@RequestMapping(value = "/", method = RequestMethod.GET)
@ApiOperation(value = "根据汽车id查询汽车", notes = "根据车辆编号查询", code = 200, produces = "application/json")

Demo示例

@Controller
@RequestMapping("car")
public class CarController {
    @Autowired
    CarService carService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询所有汽车", notes = "无需添加参数", code = 200, produces = "application/json")
    public List<Car> getCars() {
        return carService.getAllCars();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据汽车id查询汽车", notes = "根据车辆编号查询", code = 200, produces = "application/json")
    public Car getCar(@ApiParam(name = "id", value = "编号", required = true) @PathVariable("id") int id) {
        return carService.getCarById((long) id);
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增车辆", notes = "需要添加名字和价格", code = 200, produces = "application/json")
    public Car addCar(@ModelAttribute Car car) {
        return carService.addCar(car);
    }
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    @ApiOperation(value = "更新车辆", notes = "更新车名或者价格", code = 200, produces = "application/json")
    public Car addCar(@PathVariable("id") int id, @ModelAttribute Car car) {
        car.setId((long)id);
        return carService.addCar(car);
    }
}
    1. 启动项目

由于maven中添加了springfox-swagger-ui的jar,所以我们可以直接访问
http://localhost:8080/swagger-ui.html 进入swagger的ui界面,功能类似于postman,可调试设置request相关参数选择请求方式触发api访问。

由于之前在Controller中已设置的 @ApiOperation(value = "根据汽车id查询汽车", notes = "根据车辆编号查询", code = 200, produces = "application/json")
所以我们可以在swaggerUI中直接check当前的文档描述。

swagger2 UI rest 调试界面,方便传输参数进行调试:

相关文章

网友评论

      本文标题:使用Swagger编写规范API接口

      本文链接:https://www.haomeiwen.com/subject/jotjqqtx.html