使用Swagger編寫規(guī)范API接口

Swagger的基本使用

概述

Swagger是一個(gè)流行的API開發(fā)框架,整合了RESTful風(fēng)格與SpringMVC的特點(diǎn)。這個(gè)框架以“開放API聲明”(OpenAPI Specification,OAS)為基礎(chǔ),對(duì)整個(gè)API的開發(fā)周期都提供了相應(yīng)的解決方案,是一個(gè)非常龐大的項(xiàng)目(包括設(shè)計(jì)、編碼和測(cè)試,幾乎支持所有語(yǔ)言)。

swagger01.png

使用方法

    1. 在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>
    1. 在現(xiàn)有springmvc的Controller請(qǐng)求上注入
@RequestMapping(value = "/", method = RequestMethod.GET)
@ApiOperation(value = "根據(jù)汽車id查詢汽車", notes = "根據(jù)車輛編號(hào)查詢", code = 200, produces = "application/json")

Demo示例

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

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查詢所有汽車", notes = "無(wú)需添加參數(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ù)車輛編號(hào)查詢", code = 200, produces = "application/json")
    public Car getCar(@ApiParam(name = "id", value = "編號(hào)", required = true) @PathVariable("id") int id) {
        return carService.getCarById((long) id);
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增車輛", notes = "需要添加名字和價(jià)格", 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 = "更新車名或者價(jià)格", code = 200, produces = "application/json")
    public Car addCar(@PathVariable("id") int id, @ModelAttribute Car car) {
        car.setId((long)id);
        return carService.addCar(car);
    }
}
    1. 啟動(dòng)項(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ù)選擇請(qǐng)求方式觸發(fā)api訪問。

由于之前在Controller中已設(shè)置的 @ApiOperation(value = "根據(jù)汽車id查詢汽車", notes = "根據(jù)車輛編號(hào)查詢", code = 200, produces = "application/json")
所以我們可以在swaggerUI中直接check當(dāng)前的文檔描述。

swagger2 UI rest 調(diào)試界面,方便傳輸參數(shù)進(jìn)行調(diào)試:
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容