1. 程式人生 > >使用 Swagger 2 構建 RESTful APIs

使用 Swagger 2 構建 RESTful APIs

1    第2-9課:使用 Swagger 2 構建 RESTful APIs

1.1     什麼是 Swagger

Swagger 是一系列 RESTful API 的工具,通過 Swagger 可以獲得專案的一種互動式文件,客戶端 SDK 的自動生成等功能。

Swagger 的目標是為 REST APIs 定義一個標準的、與語言無關的介面,使人和計算機在看不到原始碼或者看不到文件或者不能通過網路流量檢測的情況下,能發現和理解各種服務的功能。當服務通過 Swagger 定義,消費者就能與遠端的服務互動通過少量的實現邏輯。類似於低階程式設計介面,Swagger 去掉了呼叫服務時的很多猜測。 

Swagger(絲襪哥)是世界上最流行的 API 表達工具。

Swagger 是一個簡單但功能強大的 API 表達工具。它具有地球上最大的 API 工具生態系統,數以千計的開發人員,使用幾乎所有的現代程式語言,都在支援和使用 Swagger。使用 Swagger 生成 API,我們可以得到互動式文件,自動生成程式碼的 SDK 以及 API 的發現特性等。

使用 Spring Boot 整合 Swagger 的理念是,使用註解來標記出需要在 API 文件中展示的資訊,Swagger 會根據專案中標記的註解來生成對應的 API 文件。Swagger 被號稱世界上最流行的 API 工具,它提供了 API 管理的全套解決方案,API 文件管理需要考慮的因素基本都包含,這裡將講解最常用的定製內容。

1.2     快速上手

Spring Boot 整合 Swagger 2.X 很簡單,需要引入依賴並做基礎配置即可,下面我們來感受一下。

1.2.1   新增依賴包

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0
</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

1.2.2   建立 SwaggerConfig 配置類

@Configuration
@EnableSwagger2
public class SwaggerConfig {
}

在 SwaggerConfig 的類上新增兩個註解:

  • @Configuration,啟動時載入此類
  • @EnableSwagger2,表示此專案啟用 Swagger API 文件

在 SwaggerConfig 中新增兩個方法:

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            // 自行修改為自己的包路徑
            .apis(RequestHandlerSelectors.basePackage("com.neo.xxx"))
            .paths(PathSelectors.any())
            .build();
}

此方法使用 @Bean,在啟動時初始化,返回例項 Docket(Swagger API 摘要),這裡需要注意的是 .apis(RequestHandlerSelectors.basePackage("com.neo.xxx")) 指定需要掃描的包路徑,只有此路徑下的 Controller 類才會自動生成 Swagger API 文件。

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("客戶管理")
            .description("客戶管理中心 API 1.0 操作文件")
            //服務條款網址
            .termsOfServiceUrl("http://www.ityouknow.com/")
            .version("1.0")
            .contact(new Contact("純潔的微笑", "http://www.ityouknow.com/", "[email protected]"))
            .build();
}

這塊配置相對重要一些,主要配置頁面展示的基本資訊包括,標題、描述、版本、服務條款、聯絡方式等,檢視 ApiInfo 類的原始碼還會發現支援 license 配置等。

public class ApiInfo {
    public static final Contact DEFAULT_CONTACT = new Contact("", "", "");
    public static final ApiInfo DEFAULT;
    private final String version;
    private final String title;
    private final String description;
    private final String termsOfServiceUrl;
    private final String license;
    private final String licenseUrl;
    private final Contact contact;
    private final List<VendorExtension> vendorExtensions;
    //...
 
}

以上資訊皆可在此方法進行配置,也可以使用預設值。配置完成之後啟動專案,在瀏覽器中輸入網址 http://localhost:8080/swagger-ui.html,即可看到上面的配置資訊,效果如下:

 

訪問地址後,發現頁面存在這樣一句話:No operations defined in spec!,意思是沒有找到相關的 API 內容,這是因為還沒有新增對應的 Controller 資訊,接下來結合程式碼一一介紹各個註解的使用。

1.3     Swagger 常用註解

Swagger 通過註解表明該介面會生成文件,包括介面名、請求方法、引數、返回資訊等,常用註解內容如下:

作用範圍

API

使用位置

協議集描述

@Api

用於 Controller 類上

協議描述

@ApiOperation

用在 Controller 的方法上

非物件引數集

@ApiImplicitParams

用在 Controller 的方法上

非物件引數描述

@ApiImplicitParam

用在 @ApiImplicitParams 的方法裡邊

響應集

@ApiResponses

用在 Controller 的方法上

響應資訊引數

@ApiResponse

用在 @ApiResponses 裡邊

描述返回物件的意義

@ApiModel

用在返回物件類上

物件屬性

@ApiModelProperty

用在出入引數物件的欄位上

在第 2-8 課講解的示例專案基礎上,新增 RESTful API 文件示例。

1.3.1   @Api 的使用

Api 作用在 Controller 類上,做為 Swagger 文件資源,該註解將一個 Controller(Class)標註為一個 Swagger 資源(API)。在預設情況下,Swagger-Core 只會掃描解析具有 @Api 註解的類,而會自動忽略其他類別資源(JAX-RS endpoints、Servlets 等)的註解。

使用示例:

@Api(value = "訊息", description = "訊息操作 API", position = 100, protocols = "http")
@RestController
@RequestMapping("/")
public class MessageController {
}

與 Controller 註解並列使用,屬性配置如表所示:

屬性名稱

備註

value

url 的路徑值

tags

如果設定這個值,value 的值會被覆蓋

description

對 API 資源的描述

produces

For example, "application/json, application/xml"

consumes

For example, "application/json, application/xml"

protocols

Possible values: http, https, ws, wss

authorizations

高階特性認證時配置

hidden

配置為 true 將在文件中隱藏

重啟專案之後,在瀏覽器中輸入網址 http://localhost:8080/swagger-ui.html#/message-controller,可以看到如下效果:

 

自動將 MessageController 內的方法都添加了對映,並標明瞭每種方法的請求方式。

1.3.2   @ApiOperation 的使用

ApiOperation 定義在方法上,描述方法名、方法解釋、返回資訊、標記等資訊。

使用示例:

@ApiOperation(
            value = "訊息列表",
            notes = "完整的訊息內容列表",
            produces="application/json, application/xml",
            consumes="application/json, application/xml",
            response = List.class)
@GetMapping(value = "messages")
public List<Message> list() {
}

屬性名稱

備註

value

url 的路徑值

tags

如果設定這個值、value的 值會被覆蓋

produces

For example, "application/json, application/xml"

consumes

For example, "application/json, application/xml"

protocols

Possible values: http, https, ws, wss

authorizations

高階特性認證時配置

hidden

配置為 true 將在文件中隱藏

response

返回的物件

responseContainer

這些物件是有效的 "List", "Set" or "Map",其他無效

httpMethod

"GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"OPTIONS" and "PATCH"

code

http 的狀態碼 預設 200

extensions

擴充套件屬性

重啟專案之後,在瀏覽器中輸入網址 http://localhost:8080/swagger-ui.html#/message-controller/listUsingGET,可以看到如下效果:

 

1.3.3   @ApiImplicitParams 和 @ApiImplicitParam 的使用

@ApiImplicitParams 用於描述方法的返回資訊,和 @ApiImplicitParam 註解配合使用;@ApiImplicitParam 用來描述具體某一個引數的資訊,包括引數的名稱、型別、限制等資訊。

使用示例:

@ApiOperation(value = "新增訊息", notes = "根據引數建立訊息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "訊息 ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "text", value = "正文", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),
})
@PostMapping(value = "message")
public Message create(Message message) {
}

屬性名稱

備註

name

接收引數名

value

接收引數的意義描述

required

引數是否必填值為 true 或者 false

dataType

引數的資料型別只作為標誌說明,並沒有實際驗證

paramType

查詢引數型別,其值:
path 以地址的形式提交資料
query 直接跟引數完成自動對映賦
body 以流的形式提交,僅支援 POST
header 引數在 request headers 裡邊提交
form 以 form 表單的形式提交 僅支援 POST

defaultValue

預設值

重啟專案之後,在瀏覽器中輸入網址 http://localhost:8080/swagger-ui.html#/message-controller/createUsingPOST,可以看到如下效果:

 

1.3.4   @ApiResponses 和 @ApiResponse 的使用

@ApiResponses 主要封裝方法的返回資訊和 @ApiResponse 配置起來使用,@ApiResponse 定義返回的具體資訊包括返回碼、返回資訊等。

使用示例:

@ApiOperation(value = "修改訊息", notes = "根據引數修改訊息")
@PutMapping(value = "message")
@ApiResponses({
        @ApiResponse(code = 100, message = "請求引數有誤"),
        @ApiResponse(code = 101, message = "未授權"),
        @ApiResponse(code = 103, message = "禁止訪問"),
        @ApiResponse(code = 104, message = "請求路徑不存在"),
        @ApiResponse(code = 200, message = "伺服器內部錯誤")
})
public Message modify(Message message) {
}

屬性名稱

備註

code

http 的狀態碼

message

描述

response

預設響應類 Void

reference

參考

responseHeaders

封裝返回資訊

responseContainer

字串

重啟專案之後,在瀏覽器中輸入網址 http://localhost:8080/swagger-ui.html#/message-controller/modifyUsingPUT,可以看到如下效果:

 

1.3.5   @ApiModel 和 @ApiModelProperty 的使用

在實際的專案中我們常常會封裝一個物件作為返回值,@ApiModel 就是負責描述物件的資訊,@ApiModelProperty 負責描述物件中屬性的相關內容。

使用示例:

@ApiModel(description = "響應物件")
public class BaseResult<T> {
    private static final int SUCCESS_CODE = 0;
    private static final String SUCCESS_MESSAGE = "成功";
 
    @ApiModelProperty(value = "響應碼", name = "code", required = true, example = "" + SUCCESS_CODE)
    private int code;
    @ApiModelProperty(value = "響應訊息", name = "msg", required = true, example = SUCCESS_MESSAGE)
    private String msg;
    @ApiModelProperty(value = "響應資料", name = "data")
    private T data;
}

屬性配置如下表所示:

屬性名稱

備註

value

屬性描述

name

如果配置覆蓋屬性名稱

allowableValues

允許的值

access

可以不配置

notes

沒有使用

dataType

資料型別

required

是否為必傳引數

position

顯示的順序位置

hidden

是否因此

example

舉例

readOnly

只讀

reference

引用

這樣我們在 Controller 中封裝返還資訊時就可以這樣操作:

@PatchMapping(value="/message/text")
public BaseResult<Message> patch(Message message) {
    Message messageResult=this.messageRepository.updateText(message);
    return BaseResult.successWithData(messageResult);
}

重啟專案之後,在瀏覽器中輸入網址 http://localhost:8080/swagger-ui.html,點解頁面 Models 摺疊項,可以看到如下效果:

 

以上就是在專案中最常用的一些註解,靈活地利用這些註解就可以自動構建出清晰的 API 文件。

1.4     Try it out

使用 Swagger 建立的線上 API 還有一個非常強大的功能,可以在頁面直接測試介面的可用性,這樣在前端和後端介面調試出現問題時,可以非常方便地利用此功能進行介面驗證。在上面引數講解過程中,我們發現每個介面描述右側都有一個按鈕 try it out,單擊 try it out 按鈕即可進入表單頁面,如下:

 

在表單頁面新增相關欄位後,單擊“Execute”按鈕就會將請求傳送到後臺,從而進行介面驗證,通過按鈕下面的命令可以看出,實際上是使用了 curl 命令進行的 post 測試:

curl -X POST "http://localhost:8080/message?id=6&summary=%E8%BF%99%E6%98%AF%E4%B8%80%E4%B8%AA%E6%B6%88%E6%81%AF&text=hello" -H "accept: */*"

在後端調整 Swagger 方法上對應引數,即可看到 curl 命令引數的變化。

1.5     總結

通過這節課的學習我們掌握了在 Spring Boot 專案中使用 Swagger,利用 Swagger 的相關注解可以容易地構建出豐富的 API 文件。使用 Swagger 之後可以幫助生成標準的 API 說明文件,避免介面互動中的低效溝通問題,Swagger 做為強大的 API 生成框架其實還有更多的功能,大家有機會可以線上下繼續學習。

點選這裡下載原始碼