# Laravel10 使用 Swagger 產出API文件 ## 前言 每次完成API開發後還要花額外的時間撰寫API文件讓你失去寶貴的青春了嗎 當寫API文件可以像寫程式一樣輕鬆時,誰不想寫呢 就讓我們來加入這個好用的工具吧! ## 安裝套件:l5-swagger ``` composer require darkaonline/l5-swagger ``` ## 加入註解的程式碼 ### 1. 加入swagger的唯一info與server資訊 - 建立一個swagger provider ``` php artisan make:provider SwaggerServiceProvider ``` - 將服務註冊進config/app.php - 加入swagger註解進SwaggerServiceProvider.php,註解參考範例:https://github.com/DarkaOnLine/L5-Swagger/wiki/Examples ```php //... /** * @OA\Info( * version="1.0.0", * title="Your title", * description="Your description", * @OA\Contact( * email="your-email@example.com", * name="Your Name" * ) * ) * @OA\Server(url="http://yourdomain/api") */ public function boot() { // } //... ``` ### 2. 在controller內加入swagger註解 UserController.php ```php //... /** * @OA\Get( * tags={"User"}, * path="/api/users", * summary="Get list of users sorted by deposit", * description="Returns all users sorted in descending order by their deposit", * @OA\Response( * response=200, * description="OK" * ) * ) */ public function index() { // } //... ``` ## 生成API文件 `php artisan l5-swagger:generate` ## 訪問文件連結 預設為`根目錄/api/documentation`,這邊為:http://127.0.0.1:8000/api/documentation/ **成功訪問**  ## P.S. 不要保留舊檔案,為了這問題,在generate時不斷遇到錯誤`Unable to merge @OA\Post()` ~~卡了至少半小時...,直到開啟新專案測試才發現正常,在這之前甚至issue回報都寫到一半了~~ ## 參考資料 - 套件官方教學資料:https://github.com/DarkaOnLine/L5-Swagger/wiki/Installation-&-Configuration - https://jamie-life-coding.site/2022/09/implement-l5-swagger-to-laravel/
×
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