1. 程式人生 > >如何優雅的“編寫”api介面文件

如何優雅的“編寫”api介面文件

前言

  今天我需要把之前寫的介面整理成文件,老大給了意見用swagger搞,我像發現新大陸一樣的興奮,迫不及待得去“佔有”它。 
  Swagger很容易上手,我花了十幾分鍾就搞定了。正好接著之前的如何優雅的格式化介面,這裡再說一下SpringBoot整合Swagger的簡單過程吧

Swagger介紹

  每每get新的技能想分享的時候,按照套路來講,需要有一個版塊將該技能的“前世今生”介紹個遍,但就我接觸到完成配置不超過半小時,我覺得讓我完完整整的介紹有點太虛了,所以,最好的介紹就是下面的官網 
http://swagger.io/ 
http://swagger.io/irc/ 這個是實時聊天室,剛剛和老外溝通了一番“how are you?fine thk you.and you?” 

https://github.com/swagger-api/swagger-core/wiki/Annotations#apimodel 這個是一些註解的api 
Swagger有三個模組

  • Swagger Editor
  • Swagger UI
  • Swagger Codegen

      我使用的是Swagger UI,我個人的理解就是“使用Swagger相關的註解並啟動服務後,就可以在對應的頁面檢視API並測試”,先看一下最終的介面 
       
    api.png
    介面描述、引數型別、返回示例線上除錯都給你搞定了。你還在猶豫什麼,趕快checkou程式碼,試一試吧

整合

  我接著之前的程式碼的寫(可以在我的GitHub上瀏覽,或者直接clone到本地再切換到api-norms

分支),這裡要說一下,使用Springboot整合Swagger賊JB簡單,相比較而言,SpringMVC就比較複雜了,這裡暫且不談(以後可能也不會談了,自從我使用了Springboot之後,就已經開始拋棄SpringMVC了)

maven依賴

老規矩上配置

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version
>
</dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

新增Swagger註解

  在Application上直接新增@EnableSwagger2,注意版本,官網上的版本還沒有更新到最新的,最新的在Github上看,配置後的程式碼

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by wangxc on 2017/3/9.
 */
@SpringBootApplication
@EnableSwagger2
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

可以了,接下來就是描述介面的註解了!在Controller層,做如下配置

package com.quick.api;


import com.quick.po.Address;
import com.quick.utils.BaseResp;
import com.quick.utils.ResultStatus;
import io.swagger.annotations.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IDEA
 * User: vector
 * Data: 2017/4/12
 * Time: 8:41
 * Description:
 */
@RestController
@RequestMapping("/api")
@Api("springboot整合swagger2") // Swagger UI 對應api的標題描述
public class WebController {

    @ApiOperation("獲取地址資訊") // 單個介面的描述
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="province",dataType="String",required=true,value="省",defaultValue="廣東省"),// 每個引數的型別,名稱,資料型別,是否校驗,描述,預設值(這些在介面上有展示)
            @ApiImplicitParam(paramType="query",name="area",dataType="String",required=true,value="地區",defaultValue="南山區"),
            @ApiImplicitParam(paramType="query",name="street",dataType="String",required=true,value="街道",defaultValue="桃園路"),
            @ApiImplicitParam(paramType="query",name="num",dataType="String",required=true,value="門牌號",defaultValue="666")
    })
    @ApiResponses({
            @ApiResponse(code=400,message="請求引數沒填好"), // 響應對應編碼的描述
            @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對")
    })
    @RequestMapping(value = "/address",method = RequestMethod.POST)
    public BaseResp<Address> getAddressInfo(@RequestParam(value = "province")String province,
                                   @RequestParam(value = "area")String area,
                                   @RequestParam(value = "street")String street,
                                   @RequestParam(value = "num")String num){

        if(StringUtils.isEmpty(province)||StringUtils.isEmpty(area)||StringUtils.isEmpty(street)||StringUtils.isEmpty(num)){
            return new BaseResp(ResultStatus.error_invalid_argument);
        }
        Address address = new Address();
        address.setProvince(province);
        address.setArea(area);
        address.setStreet(street);
        address.setNum(num);
        return new BaseResp(ResultStatus.SUCCESS,address);

    }

    @ApiOperation("獲取地址資訊")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="province",dataType="String",required=true,value="省",defaultValue="廣東省"),
            @ApiImplicitParam(paramType="query",name="area",dataType="String",required=true,value="地區",defaultValue="南山區"),
            @ApiImplicitParam(paramType="query",name="street",dataType="String",required=true,value="街道",defaultValue="桃園路"),
            @ApiImplicitParam(paramType="query",name="num",dataType="String",required=true,value="門牌號",defaultValue="666")
    })
    @ApiResponses({
            @ApiResponse(code=400,message="請求引數沒填好"),
            @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對")
    })
    @RequestMapping(value = "/address/list",method = RequestMethod.POST)
    public BaseResp<List<Address>> getAddressList(@RequestParam(value = "province")String province,
                                             @RequestParam(value = "area")String area,
                                             @RequestParam(value = "street")String street,
                                             @RequestParam(value = "num")String num){

        if(StringUtils.isEmpty(province)||StringUtils.isEmpty(area)||StringUtils.isEmpty(street)||StringUtils.isEmpty(num)){
            return new BaseResp(ResultStatus.error_invalid_argument);
        }
        Address address = new Address();
        address.setProvince(province);
        address.setArea(area);
        address.setStreet(street);
        address.setNum(num);
        List<Address> lists = new ArrayList<>();
        lists.add(address);
        lists.add(address);
        lists.add(address);
        return new BaseResp(ResultStatus.SUCCESS,lists);

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90

我只是在原來的基礎上添加了下面註解

名稱解釋
@Api()將類標記為一種Swagger資源。
@ApiOperation()描述針對特定路徑的操作或通常是 http 方法。
@ApiImplicitParams允許多個 ApiImplicitParam 物件列表的包裝。
@ApiImplicitParam表示 api 操作中的單個引數。
@ApiResponses允許多個 ApiResponse 物件列表的包裝。
@ApiResponse描述操作的可能響應。

更多的看這裡

就這麼簡單,一個基本而又強大的API文件就整理好了!

啟動

正常的啟動SpringBoot,你會發現控制檯輸出了這些內容

2017-05-03 21:42:52,975  INFO ClassOrApiAnnotationResourceGrouping:100 - Group for method getAddressList was springboot整合swagger2
2017-05-03 21:42:52,986  INFO ClassOrApiAnnotationResourceGrouping:100 - Group for method getAddressList was springboot整合swagger2
  • 1
  • 2

說明Swagger已經成功跑起來了,接下來開啟瀏覽器,輸入你連結 
yourdomain/swagger-ui.html 
我的是

相信你看了介面並四處點點之後,就會對上面註解的含義有了更進一步的瞭解~

後記

  這裡展示的只是Swagger最基本的功能,更多強大的功能如果後面有運用,我會持續更新的。 
  目前我在看api尋找SwaggerUI輸入檔案的測試,因為我有個介面需要上傳檔案,等我搞定,再來分享吧!!! 
  

歡迎進入我的個人部落格瀏覽