close

最近實習在用Spring Boot框架寫JAVA backend的相關API,發現除了Postman以外,學長們介紹了個好用的工具Swagger,讓我覺得要一定要好好了解這模組,Swagger提供UI介面使API清楚的條列式呈現,不只可以加入說明,還可以在Post出去的Request body內容放入預設值,讓我在測試結果省了不少時間和功夫,除此之外,也可以當作是前後端人員溝通的工具(有點像是使用者文件的概念),下面來簡單做個使用筆記吧!

(1)要先在Maven POM加入下面的宣告,讓他幫我把相關的jar檔抓進來

        <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>

如果是build.gradle 則是加入下面的宣告,讓他幫我把相關的jar檔抓進來

dependencies {
    compile 'io.springfox:springfox-swagger2:2.8.0'
    compile 'io.springfox:springfox-swagger-ui:2.8.0'
    compile 'io.springfox:springfox-data-rest:2.8.0'
}

如果是JDK8以下的話要額外加入,否則會報錯

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>

注意: 我之前測試一直出現error message是因為我version使用到2.2.0,記得要用最新的版本才不會出現錯誤(如下圖)

1.png

(2)配置Swagger config檔案

Springfox 提供了@EnableSwagger2這個Annotation標示出Swagger支援我們這個Application,並嵌入在程式裡面,配置檔要自己額外加入,就在目錄下建立SwaggerConfig.java,並在裡面加入前面講的@EnableSwagger2以及@Configuration,讓Annotation幫我們做些底層的事情,最後呈現在Swagger UI介面上面,配置的程式碼如下。

..
..
@Configuration
@EnableSwagger2
public class SwaggerConf {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.kevin.controller"))
                .paths(PathSelectors.any())//paths(PathSelectors.regex("/.*"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("標題:Spring Boot中使用Swagger2建構RESTful APIs")
                .description("相關說明")
                .termsOfServiceUrl("https://www.pixnet.net/pcard/B0212066/")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .version("1.0.0")
                .build();
    }
}

下圖對應上面的程式碼,這邊只需要修改範例程式的一些部分即可,特別要注意backPackage要指定到我放controller的java檔位址,要注意要把SwaggerConf.java放在Application主程式可以讀取到的位址(例如Application.jave放在com.kevin這個package,SwaggerConf.java就要放在同個package或是子package),否則會出現Spring抓不到的問題。

1.png

(2)在controller增加API說明

..
..
//http://localhost:8080/swagger-ui.html

@Api(tags="UserController",description="類別檔案說明")
@RestController
public class UserController {
	  @ApiOperation(value="My first api", notes="API說明文字")
	  @PostMapping("/api/v1")
	  public ResponseEntity hello(@RequestBody UserRequestDto dto){
		  System.out.println(dto);
	      return ResponseEntity.ok("Hello World");
	  }
}

我們在@RestController上加入@Api目的是要在Class增加說明,通常可以不加,就是原本的類別名稱。在Mapping的Annotation上面加入@ApiOperation(value="My first api", notes="顯示說明文字")目的是要增加API的說明,參數value通常寫一些這隻API的功用,例如:get user info...而notes就是更詳細的說明了。

簡報1.png

這邊看到@Api的description參數已經被depreciated,也是可以用,但是建議用另外一種方式來產生Controller的說明,如下

在SwaggerConfig裡面紅色那段程式碼,對tags進行操作,有幾個controller就new出幾個物件放進tags的參數裡面,new Tag()的第一個參數放tag名稱,第二個是要對這個配置tag的controller做說明

@Configuration
@EnableSwagger2
public class SwaggerConf {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .tags(new Tag("UserController", "類別檔案說明"),new Tag("TestController", "測試檔案說明"))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.kevin.controller"))
                .paths(PathSelectors.any())//paths(PathSelectors.regex("/.*"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("標題:Spring Boot中使用Swagger2建構RESTful APIs")
                .description("相關說明")
                .termsOfServiceUrl("https://www.pixnet.net/pcard/B0212066/")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .version("1.0.0")
                .build();
    }
}

加入Http status狀態碼說明文字

    @ApiOperation(value = "View a list of available employees", response = List.class)
 
    @ApiResponses(value = {
 
        @ApiResponse(code = 200, message = "Successfully retrieved list"),
 
        @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
 
        @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
 
        @ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
 
    }) //加很多狀況
............
@ApiResponses(value = {@ApiResponse(code = 200, message = "書本資訊")})      //只加單一行

DTO的配置及使用

        @ApiOperation(value = "API info", notes = "API detailed info")
        @ApiResponses(value = {@ApiResponse(code = 200, message = "http status info")})
        @PostMapping("/api/v2")
        public UserRequestDto get(
                @ApiParam(required = true,value = "請傳入UserRequestDto的格式") @RequestBody UserRequestDto dto) {
            return dto;
        }..

@ApiParam就是傳入參數的說明及範例顯示,例如我傳入UserRequestDto這物件,就可以加入@ApiParam,也可以加入value="..."

1564313850962.jpg

..
..
@ApiModel(description = "All details about the User ")
public class UserRequestDto {
    @ApiModelProperty(notes = "The database generated User name",position=1,value = "username",example="xingguo")
    public String userName;
    @ApiModelProperty(notes = "The database generated User age",position=2,value = "age",example="24")
    public Integer age;
    @ApiModelProperty(notes = "The database generated User phone",position=3,value = "phone",example="0975123654")
    public String phone;
}

通常用Post在Request body包json傳入時候,都習慣使用Dto來接收json,而dto裡面習慣加入Swagger的一些Annotation,讓我們在測試的時候可以更加快速。這邊有些常用的參數。

notes: 對API資源做描述

hiddem=true/false: 此屬性隱藏起來

position: Swagger UI介面的傳入json順序,1就是第一個,2就是第二個.....

required=true/false: 是否為必填的field

value: 在Example的json格式中,key值的腳色,就是我們的DTO的物件屬性

example: 範例的值,就是物件屬性給他的值預設要多少

2.png

 

(3)輸入網址來測試

一般來說都是在我們預設的localhost端來做測試,服務啟動起來後,就可以輸入下面URL進入Swagger的UI

http://localhost:8080/swagger-ui.html

成功畫面如下:

1564310789363.jpg

Reference:

https://dzone.com/articles/spring-boot-2-restful-api-documentation-with-swagg

https://mvnrepository.com/artifact/io.springfox/springfox-swagger2

arrow
arrow
    文章標籤
    Swagger 2 Spring Boot Java
    全站熱搜

    KV 發表在 痞客邦 留言(1) 人氣()