Swagger的基本使用
概述
Swagger是一個流行的API開發(fā)框架,整合了RESTful風(fēng)格與SpringMVC的特點(diǎn)。這個框架以“開放API聲明”(OpenAPI Specification核畴,OAS)為基礎(chǔ)匀伏,對整個API的開發(fā)周期都提供了相應(yīng)的解決方案蝴蜓,是一個非常龐大的項(xiàng)目(包括設(shè)計(jì)、編碼和測試剖膳,幾乎支持所有語言)。
使用方法
- 在mavem項(xiàng)目環(huán)境中注入以下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>
- 在現(xiàn)有springmvc的Controller請求上注入
@RequestMapping(value = "/", method = RequestMethod.GET)
@ApiOperation(value = "根據(jù)汽車id查詢汽車", notes = "根據(jù)車輛編號查詢", code = 200, produces = "application/json")
Demo示例
@Controller
@RequestMapping("car")
public class CarController {
@Autowired
CarService carService;
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "查詢所有汽車", notes = "無需添加參數(shù)", code = 200, produces = "application/json")
public List<Car> getCars() {
return carService.getAllCars();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根據(jù)汽車id查詢汽車", notes = "根據(jù)車輛編號查詢", 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);
}
}
- 啟動項(xiàng)目
由于maven中添加了springfox-swagger-ui的jar,所以我們可以直接訪問
http://localhost:8080/swagger-ui.html 進(jìn)入swagger的ui界面岭辣,功能類似于postman吱晒,可調(diào)試設(shè)置request相關(guān)參數(shù)選擇請求方式觸發(fā)api訪問。
由于之前在Controller中已設(shè)置的 @ApiOperation(value = "根據(jù)汽車id查詢汽車", notes = "根據(jù)車輛編號查詢", code = 200, produces = "application/json")
所以我們可以在swaggerUI中直接check當(dāng)前的文檔描述易结。