# Swagger建立UI上的API分頁 ### 簡介 在大型專案中,API 數量非常龐大,使用 Swagger UI 查看所有 API 時會很雜亂,因此我們使用 springdoc-openapi 的分頁 (Groups) 功能,依功能模組分組 API,讓 Swagger UI 頁面上有多個標籤(Tabs)可選擇,清晰瀏覽不同群組的 API。 ### 前置作業 📁 Swagger 分頁設定檔位置有兩種 | 類型 | 檔案名稱 | 放置路徑 | |------------------|------------------------|---------------------------------| | Properties 格式 | `application.properties` | `src/main/resources/` | | YAML 格式 | `application.yml` | `src/main/resources/` | 備註:本教學採用 Properties 教學 ### 啟用分頁功能 ``` java= springdoc.api-docs.groups.enabled=true springdoc.swagger-ui.tagsSorter=alpha ``` ### 分頁群組範例配置 ``` java= springdoc.group-configs[0].group=1. 系統管理 springdoc.group-configs[0].paths-to-match=/api/v*/system/**,/api/v*/file/** springdoc.group-configs[0].packages-to-scan=com.example.project.api springdoc.group-configs[1].group=2. 會員管理 springdoc.group-configs[1].paths-to-match=/api/v*/member/**,/api/v*/login/** springdoc.group-configs[1].packages-to-scan=com.example.project.api springdoc.group-configs[2].group=3. 文章管理 springdoc.group-configs[2].paths-to-match=/api/v*/announcement/** springdoc.group-configs[2].packages-to-scan=com.example.project.api ``` - group:顯示於 Swagger UI 的分頁名稱,建議用數字排序方便識別 - paths-to-match:指定符合的 API 路徑,支援通配符 * 和 ** - packages-to-scan:指定要掃描的 Controller 包路徑,避免掃到不相關的 Controller ### Controller 設計 路徑要與 paths-to-match 配合 ```java= @RestController @RequestMapping("/api/v1/announcement") @Tag(name = "3. 文章管理") public class AnnouncementController { @PostMapping("/create") public ResponseEntity<?> createAnnouncement(@RequestBody CreateRequest req) { // ... } } ``` 備註:建議版本號放在 /api/v1/ 等級,方便統一管理與分頁匹配 ### 總結 以上就是Swagger UI上如果想要讓API不這麼凌亂的全部散落在同一頁,可以這樣做設定。
×
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