Try   HackMD

Laravel10 使用 Swagger 產出API文件

前言

每次完成API開發後還要花額外的時間撰寫API文件讓你失去寶貴的青春了嗎
當寫API文件可以像寫程式一樣輕鬆時,誰不想寫呢
就讓我們來加入這個好用的工具吧!

安裝套件:l5-swagger

composer require darkaonline/l5-swagger

加入註解的程式碼

1. 加入swagger的唯一info與server資訊

  • 建立一個swagger provider
php artisan make:provider SwaggerServiceProvider
//...
/**
* @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

//...
/**
 * @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/

成功訪問

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

P.S.

不要保留舊檔案,為了這問題,在generate時不斷遇到錯誤Unable to merge @OA\Post()
卡了至少半小時,直到開啟新專案測試才發現正常,在這之前甚至issue回報都寫到一半了

參考資料