# Swagger基礎教學 ### 簡介 什麼是Swagger? Swagger UI 是一個開源工具,能夠根據程式專案中定義的 RESTful API,產生文件網頁。若有人想要串接這些 API,可以前往網頁進行「試用」。 來源:https://en.wikipedia.org/wiki/Swagger_(software) ---- ### 如何在專案引進Swagger? 在pom.xml 檔案添加依賴即可。 網址:https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui/2.8.9 ```xml= <!-- Swagger --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.8.9</version> </dependency> ``` ---- ### 撰寫範例 此範例以Java Spring Boot專案撰寫。 建置兩個Controller,分別為HelloSpringBootController及HelloNameController #### 【HelloSpringBootController】 ```java= package test; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @RestController @RequestMapping("/api") @Tag(name = "測試") @Slf4j public class HelloSpringBootController { @Operation(summary = "測試") @GetMapping("/hello") public String hello() { log.info("回應Hello"); System.out.println("Hello Spring Boot!"); return "Hello Spring Boot!"; } } ``` #### 【HelloNameController】 ```java= package test; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") @Tag(name = "測試") @Slf4j public class HelloNameController { @Operation(summary = "輸入名字後,回傳Hello + 名字") @GetMapping("/helloandname") public String greet( @Parameter(description = "請輸入名字", required = true) final @RequestParam (name = "name") String name) { log.info("輸入名字"); log.info("user[{}] with input: {}", name, name); System.out.println("Hello, " + name + "!"); return "Hello, " + name + "!"; } } ``` ---- 啟動專案後 前往網址 http://localhost:8080/swagger-ui/index.html 就能看到了。  (圖1) Swagger介面  (圖2) 測試API & IDE查看Console訊息 ---- ### 總結 以上就是Swagger的簡單介紹及範例,若有興趣可以再自行研究看看。 ---- > 歡迎隨意引用或拷貝,若有涉及侵權概不負責。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up