laravel環境にswaggerを入れる

未分類


laravelでswaggerを入れる場合にパッケージ入れるとしたら

  • darkaonline/l5-swagger
  • zircote/swagger-php

の2択になりそうです。

両方ともつかい勝手を読んでみたのですが「darkaonline/l5-swagger」の方がインストールが簡単、jsonの吐き出しを.envに書き足すと更新してくれる。の2点で良さそうです。

darkaonline/l5-swaggerを使ってみる。

どのように使うかと言うと前提としてコントローラーにjsonファイルを書き出し元となる記述を書くとjsonを吐き出すと言う仕様があります。

まずはインストールから、docker環境の場合でメモリーオーバーになってしまう場合は下記コマンドで実行

docker-compose exec コンテナ名 bash -c "COMPOSER_MEMORY_LIMIT=-1 composer require darkaonline/l5-swagger"

インストールが完了しましたら。swaggerの表題になる設定をapp\swagger.php app\controller\Swagger.php設定します。
例としては下記の通り、コメントアウトされてますがOKです。

<?php

/**
 * API情報
 * @OA\Info(
 *  title="API Example",
 *  description="description",
 *  version="1.0.0",
 * )
 *
 *  サーバー情報
 *  @OA\Server(
 *   description="OpenApi host",
 *   url="http://localhost:3000"
 * )
 *
 * セキュリティスキーマ
 * @OA\SecurityScheme(
 *     securityScheme="bearerAuth",
 *     type="http",
 *     scheme="bearer",
 *     description="Entrer le token JST"
 * )
 */

この設定のみだと下記が表示されてしまう。

  Required @OA\PathItem() not found

コントローラーに何かの設定を記述する必要がある。
次にコントローラーに記述の追加。

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserApiController extends Controller
{
    /*下記を追加*/
    /**
     * @OA\Get(
     *     path="/user",
     *     operationId="user",
     *     tags={"user"},
     *     summary="ユーザー",
     *     description="user用",
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(
     *                 property="message",
     *                 type="string",
     *                 description="メッセージ",
     *                 example="massage"
     *             )
     *         )
     *     )
     * )
     */

    public function getUser()
    {

postの場合

引用
https://qiita.com/horikeso/items/34ad3c91a6864e868d34

/**
 * @OA\Post(
 *   path="/api/example/{id}",
 *   summary="具体例が無かったので寄せ集めてみた",
 *   @OA\RequestBody(
 *     required=true,
 *     @OA\JsonContent(
 *       type="object",
 *       required={"number", "text"},
 *       @OA\Property(
 *         property="number",
 *         type="integer",
 *         format="int32",
 *         example=1,
 *         description="リクエストボディのjsonのプロパティの例"
 *       ),
 *       @OA\Property(
 *         property="text",
 *         type="string",
 *         example="text",
 *         description="リクエストボディのjsonのプロパティの例"
 *       )
 *     )
 *   ),
 *   @OA\Parameter(
 *     name="id",
 *     in="path",
 *     required=true,
 *     description="パスからのパラメータ例",
 *     @OA\Schema(type="string")
 *   ),
 *   @OA\Parameter(
 *     name="queryString",
 *     in="query",
 *     required=true,
 *     description="クエリーストリングからのパラメータ例",
 *     @OA\Schema(type="string")
 *   ),
 *   @OA\Response(
 *     response=200,
 *     description="OK",
 *     @OA\JsonContent(
 *       type="object",
 *       @OA\Property(
 *         property="message",
 *         type="string",
 *         description="レスポンスボディjsonパラメータの例"
 *       )
 *     )
 *   ),
 *   @OA\Response(
 *     response=400,
 *     description="Bad Request",
 *     @OA\JsonContent(
 *       type="object",
 *       @OA\Property(
 *         property="message",
 *         type="string",
 *         description="レスポンスボディjsonパラメータの例"
 *       )
 *     )
 *   ),
 *   @OA\Response(
 *     response=401,
 *     description="Unauthorized",
 *     @OA\JsonContent(
 *       type="object",
 *       @OA\Property(
 *         property="message",
 *         type="string",
 *         description="レスポンスボディjsonパラメータの例"
 *       )
 *     )
 *   ),
 *   @OA\Response(
 *     response="default",
 *     description="Unexpected Error",
 *     @OA\JsonContent(
 *       type="object",
 *       @OA\Property(
 *         property="message",
 *         type="string",
 *         description="レスポンスボディjsonパラメータの例"
 *       )
 *     )
 *   )
 * )
 */

JSONファイルの書き出し

下記コマンドでコントローラーの設定ファイルを元にjsonファイルが書き出されます。

php artisan l5-swagger:generate

毎回コマンドの実行が面倒な場合位、.envファイルに下記の設定を追加

L5_SWAGGER_GENERATE_ALWAYS=true

動作の確認

/api/documentation
配下を参照する事で可能

ルーティングに関しても下記のように設定されていればOK

実践的な使い方

こちらで一通り使い方を見ましたので、さらに実践的な使い方になります。

modelをschemaと定義して参照して定義できるようにする。

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;


/**
 *  @OA\Schema(
 *      schema="User",
 *      type="object",
 *      description="User Model",
 *      @OA\Property(
 *          property="id",
 *          description="ID",
 *          type="integer",
 *          format="int64",
 *          example="1"
 *      ),
 *      @OA\Property(
 *          property="name",
 *          description="Name",
 *          type="string",
 *          format="string",
 *          example="山田太郎"
 *      )
 * )
 *
 * @package App\Models
 */
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

このように定義する事によって

@OA\Schema(ref="#/components/schemas/User"),

と各事によって参照した呼び出しが可能となります。

認証済みルートの設定

既にセキュリティースキーマの設定はしましたが

 * セキュリティスキーマ
 * @OA\SecurityScheme(
 *     securityScheme="bearerAuth",
 *     type="http",
 *     scheme="bearer",
 *     description="Entrer le token JST"
 * )

セキュリティスキーマで設定した設定を元に下記のように記述する事でswaggerで認証ルートの記述が可能です。

     *     security={
     *         {"bearerAuth": {}}
     *     },