# API 文件|Swagger for Laravel ## 安裝步驟 ```bash= # Step 1 composer require "darkaonline/l5-swagger:6.*" # Step 2 php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" # Step 3 artisan l5-swagger:generate ``` ## 使用技巧 ### Request Body 原本 POST 是寫成 parameter 且屬性為 in="query",後來發現要寫在 body 裡。 ([參考資料](https://github.com/zircote/swagger-php/blob/master/Examples/example-object/example-object.php)) example: ``` @OA\RequestBody( @OA\MediaType( mediaType="application/json", @OA\Schema( @OA\Property( property="id", type="string" ), @OA\Property( property="name", type="string" ), example={"id": "a3fb6", "name": "Jessica Smith"} ) ) ) ``` ### 排序參數下拉選單 [參考資料](https://swagger.io/docs/specification/data-models/enums/) example: ``` @OA\Parameter( name="_sort_field", description="排序欄位", required=false, in="query", @OA\Schema( type="string", enum={ "id", "number" "created_at", "updated_at", }, example={""}, ), ), ``` ## 查看 API 文件 1. 若尚未安裝套件,請執行 composer install 進行更新 2. 在 .env 最尾端加上(此設定的目的為:之後都會自動生成文件):L5_SWAGGER_GENERATE_ALWAYS=true 3. 生成文件的指令:php artisan l5-swagger:generate 4. 至 http://localhost/api/documentation 可以查看生成的文件 步驟 1~3 僅需在專案開發初始時執行,步驟 4 為日後查看 API 文件的地址。 ## 相關連結 - [Laravel — 使用Swagger 產出API文件(主要參考此份) ](https://medium.com/@hosomikai/laravel-%E4%BD%BF%E7%94%A8swagger-%E7%94%A2%E5%87%BAapi%E6%96%87%E4%BB%B6-2f2a934c3b25) - [swagger 官方文件](https://swagger.io/docs/specification/about/) - 選擇使用的套件:[DarkaOnLine/L5-Swagger](https://github.com/DarkaOnLine/L5-Swagger) + Laravel 6.x 使用的安裝指令 `composer require "darkaonline/l5-swagger:6.*"` + 會自動安裝以下套件: 1. darkaonline/l5-swagger 2. swagger-api/swagger-ui 3. symfony/yaml 4. zircote/swagger-php - [use JWT Bearer token in swagger Laravel](https://stackoverflow.com/questions/50614594/use-jwt-bearer-token-in-swagger-laravel) in controller: ```php= /** * @OA\SecurityScheme( * type="http", * description="Login with email and password to get the authentication token", * name="Token based Based", * in="header", * scheme="bearer", * bearerFormat="JWT", * securityScheme="apiAuth", * ) */ ``` in api function: ```php= /** * @OA\Get( * path="/resources", * summary="Get the list of resources", * tags={"Resource"}, * @OA\Response(response=200, description="Return a list of resources"), * security={{ "apiAuth": {} }} * ) */ ``` ###### tags:`API` `Swagger` `Laravel`