iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 21
1
Modern Web

站在Web前端人員角度,學習 Spring Boot 後端開發系列 第 21

Day 21 - Spring Boot Swagger API 文件神器

  • 分享至 

  • xImage
  •  

中秋佳節返鄉囉!月餅吃胖胖

後端在開發API的時候若可以一面寫code一面產生文件給前端人員或外部使用者查看,那就真的是太好了,今天要介紹強大的API文件工具-Swagger ,支援非常多種語言(GO, JAVA,.NET等),當然也有支援Spring 框架。

Swagger本質上是一種接口描述語言,用於描述使用JSON表示的RESTful API 。Swagger與一組開源軟件工具一起使用,以設計,構建,記錄和使用RESTful Web服務。創建API時,可以使用Swagger工具根據代碼本身自動生成Open API文檔(自維基百科)。

讓後端API用視覺化的方式呈現也可以直接當做測試的介面,統一的格式與測試介面大幅減少溝通及維護文件的成本,以提昇效率。

pom.xml 加入swagger2 和swagger UI的依賴

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>

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

建立swagger 配置檔案 SwaggerConfig.java

透過@Configuration標註,讓spring 載入此配置

@EnableSwagger2標註來啟動swagger

ApiInfo 為springfox.documentation.service 可以加入一些基本資訊

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
                "To Do List 鐵人賽",
                "第12屆iT邦幫幫忙鐵人賽 To Do List API",
                "v1.0",
                "",
                new Contact("CaiLiWu", "",
                        "dy5025115@gmail.com"),
                "", "", Collections.emptyList());
    }
}

在Controller加入swagger

實作對每一個api節點加入標題,並自定義回傳http status code 的敘述,以下顯示[GET]/api/todos 加入swagger 敘述。

@Api 對這個控制器增加敘述

@ApiOperation("取得所有代辦事項列表") 對每一個端點加入敘述

@ApiResponses 為每個回應status code 增加自定義訊息提示

@Api(tags = "Todo list 相關api")
@RestController
@RequestMapping("/api")
public class TodoController {
    @Autowired
    TodoService todoService;

    @ApiOperation("取得所有代辦事項列表")
    @ApiResponses({
            @ApiResponse(code=401,message="沒有權限"),
            @ApiResponse(code=404,message="找不到路徑")
    })
}

最後,打開http://localhost:9100/swagger-ui.html 就會出現一下畫面。
https://ithelp.ithome.com.tw/upload/images/20200930/20118857QVGVLXvm70.png

讓我們試試看可不可以順利取得值,點擊「Try it out」按鈕,再點擊「Execute」。
https://ithelp.ithome.com.tw/upload/images/20200930/20118857XRqbFF16PO.png


上一篇
Day 20 - Spring Boot 組起來再測一遍-整合測試
下一篇
Day 22 - Spring Boot IDE 測試API好工具-REST client
系列文
站在Web前端人員角度,學習 Spring Boot 後端開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
Arthur
iT邦新手 5 級 ‧ 2020-10-01 00:48:30

終於寫到API拉~

0
NiJia
iT邦新手 5 級 ‧ 2020-10-02 23:55:14

好用吧

0
Devin
iT邦新手 4 級 ‧ 2022-02-21 18:27:08

超實用!

我要留言

立即登入留言