環境
- Laravel 8.35.1
- PHP 7.4.16
l5-swaggerを追加する
$ cd /path/to/project
$ composer require "darkaonline/l5-swagger"
書き方
@OA\Info
プロジェクト内のどこか1か所に定義すれば良い。
複数存在するとエラーになる。
/**
* @OA\Info(
* version="1.0.0",
* title="Swaggerタイトル",
* description="Swaggerの説明",
* )
*/
設定例
<?php
namespace App\Http\Controllers;
use App\Services\TestService;
use Illuminate\Http\Request;
/**
* @OA\Info(
* version="1.0.0",
* title="Swagger",
* description="",
* )
*/
class TestController extends Controller
{
・・・以下略・・・
@OA\Get
method(POST, GET, PUT, DELETE)を指定する。
tags
swaggerの分類を設定する。例えばユーザー関連のAPIならUserなど。
summary
アコーディオンを閉じていても見える説明文
description
アコーディオンを開くと見える説明文
@OA\RequestBody
リクエスト値を設定
@OA\Response
レスポンスを設定
@OA\Property
property, type, format, descriptionを設定
設定例
/**
* @OA\Post(
* path="/facilityList",
* operationId="Sample API",
* tags={"Map"},
* summary="施設情報を取得",
* description="現在地から〇km圏内の施設情報を取得するAPI",
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="lat",
* type="number",
* format="double",
* description="緯度",
* ),
* @OA\Property(
* property="lng",
* type="number",
* format="double",
* description="経度",
* ),
* ),
* )
* ),
* @OA\Response(
* response=200,
* description="正常な処理",
* @OA\JsonContent(
* type="object",
* @OA\Property(
* property="id",
* type="integer",
* description="maps.id",
* ),
* @OA\Property(
* property="name",
* type="string",
* description="施設名",
* ),
* @OA\Property(
* property="tel",
* type="string",
* description="電話番号",
* ),
* @OA\Property(
* property="lat",
* type="number",
* description="緯度",
* ),
* @OA\Property(
* property="lng",
* type="number",
* description="経度",
* ),
* @OA\Property(
* property="distance",
* type="string",
* description="現在地からの距離",
* ),
* )
* ),
* @OA\Response(
* response=400,
* description="requestデータに問題がある",
* @OA\JsonContent(
* type="object",
* @OA\Property(
* property="error message",
* type="object",
* ),
* )
* ),
* @OA\Response(response=500, description="Internal Server Error"),
* @OA\Response(response=404, description="Resource Not Found"),
* )
*/
Swagger生成コマンド
$ php artisan l5-swagger:generate
/path/to/project/storage/api-docs/api-docs.jsonが生成される。
.env
に下記を設定すれば毎回コマンドをたたかなくても更新されるので、必要に応じて追記する。
L5_SWAGGER_GENERATE_ALWAYS=true
swaggerの確認
ブラウザでドキュメントのURL( /api/documentation )にアクセスすれば、SwaggerUIを確認できる。
( 例: http://localhost/api/documentation )
※localhostの部分は個々の環境に応じて変える。