rogervila/openapi-laravel

使用 OpenAPI 规范验证 HTTP 请求和响应

0.2.0 2022-12-01 16:34 UTC

README

OpenAPI Laravel

Build Status StyleCI

Latest Stable Version Total Downloads License

OpenAPI Laravel

关于

使用 OpenAPI 规范验证 HTTP 请求和响应。

安装

使用 composer 安装此包。

composer require rogervila/openapi-laravel

Laravel 将自动发现位于 \LaravelOpenAPI\ServiceProvider 的服务提供者。

设置

该包通过规范和请求类处理 HTTP 请求。

OpenAPI 规范

首先,创建一个规范类。

# The namespace is optional, you can place specification classes anywhere.
php artisan openapi:make-specification Specifications/PetsSpecification
<?php

namespace App\Specifications;

use LaravelOpenAPI\Specification\YamlSpecification;
use LaravelOpenAPI\Specification\JsonSpecification;

// The Specification class must implement YamlSpecification or JsonSpecification interface.
class PetsSpecification implements YamlSpecification
{
    public function __invoke(): string
    {
        // As long as it returns a yaml or json string, you can resolve it as needed.
        return file_get_contents(storage_path('openapi/pets.yml'));
        
        // Another example (JSON in this case)
        // return \Cache::rememberForever(self::class, fn () => \Http::get('https://petstore3.swagger.io/api/v3/openapi.json')->body());
    }
}

OpenAPI 请求

一旦设置规范,您可以创建 OpenAPI 请求并 定义它应使用的规范

该包将根据规范处理请求验证。

  • 如果 不匹配,它将返回一个 "422 验证错误"
  • 如果 规范缺失,它将返回一个 "501 未实现" 错误。
# Requests are placed on \App\Http\Requests\OpenAPI namespace
php artisan openapi:make-request PetRequest

OpenAPI 请求继承自 \Illuminate\Foundation\Http\FormRequest,因此您可能需要根据 Laravel 文档 实现额外的规则和授权。

<?php

namespace App\Http\Requests\OpenAPI;

use LaravelOpenAPI\Request;

class PetRequest extends Request
{
    /** {@inheritDoc} */
    public function getSpecification(): string
    {
        return \App\Specifications\PetsSpecification::class;
    }
}

用法

该包包含 \LaravelOpenAPI\OpenAPI 类,作为所有包功能的访问器。

查看此存储库的 laravel 文件夹,了解在真实 Laravel 项目中如何使用此包。

示例

此示例定义了一个 FindPetByIdController 控制器,该控制器使用此包处理请求和响应。

<?php

namespace App\Http\Controllers\Pet;

use App\Http\Controllers\Controller;
use App\Http\Requests\OpenAPI\PetRequest;
use App\Http\Resources\PetResource;
use App\Models\Pet;
use Illuminate\Http\JsonResponse;
use LaravelOpenAPI\OpenAPI;

// GET /api/pet/{petId}
class FindPetByIdController extends Controller
{
    public function __invoke(PetRequest $request, int $petId): JsonResponse
    {
        if (is_null($pet = Pet::find($petId))) {
            OpenAPI::abort(JsonResponse::HTTP_NOT_FOUND)->forRequest($request);
        }

        return OpenAPI::response(new PetResource($pet))->forRequest($request);
    }
}

作者

Roger Vilà 创建

许可

OpenAPI Laravel 是开源软件,许可证为 MIT 许可证