api-skeletons / laravel-api-problem
Laravel HTTP API 问题详情
2.0.1
2024-04-13 02:57 UTC
Requires
- php: ^8.1
- doctrine/instantiator: ^2.0
- laravel/framework: ^8.0 || ^9.0 || ^10.0 || ^11.0
Requires (Dev)
- doctrine/coding-standard: ^12.0
- orchestra/testbench: ^7.41
- php-parallel-lint/php-parallel-lint: ^1.4
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.15
README
此存储库实现了 Laravel 的 RFC 7807 "HTTP API 问题详情"。
安装
运行以下命令使用 Composer 安装此库
composer require api-skeletons/laravel-api-problem
快速开始
use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem; return ApiProblem::response('Detailed Unauthorized Message', 401);
这将导致带有以下头部的 401 响应
Content-Type: application/problem+json
和内容
{ "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html", "title": "Unauthorized", "status": 401, "detail": "Detailed Unauthorized Messsge" }
使用
使用外观
您可以使用 facade 以两种方式使用 ApiProblem 对象。首先,您可以使用 facade 如快速开始中所示快速直接地返回响应。当使用 facade 时,response()
方法的参数是
response( string|Throwable $detail, int|string $status, ?string $type = null, ?string $title = null, array $additional = [] )
创建对象
当直接创建 ApiProblem 对象时,前两个参数是互换的。原因是原始对象构造函数保持不变,而 response()
函数被修改以匹配标准的 Laravel 响应 格式。
__construct( int|string $status, string|Throwable $detail, ?string $type = null, ?string $title = null, array $additional = [] )
直接创建对象的示例
use ApiSkeletons\Laravel\ApiProblem\ApiProblem; $apiProblem = new ApiProblem(401, 'Detailed Unauthorized Message'); return $apiProblem->response();
附加详情
ApiProblem 的第 5 个参数是 $additional。此数组向 JSON 响应添加了临时属性。使用此数组的一种方法是带有问题详情的 422 响应
use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem; use Illuminate\Validation\ValidationException; try { $validated = $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); } catch (ValidationException $e) { return ApiProblem::response($e->getMessage(), 422, null, null, ['errors' => $e->errors()]); }
结果为
{ "errors":{ "title":[ "The title field is required." ], "body":[ "The body field is required." ] }, "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html", "title": "Unprocessable Entity", "status": 422, "detail": "The given data was invalid." }
与异常处理器一起使用
namespace App\Exceptions; use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem; use Doctrine\ORM\EntityNotFoundException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Http\Request; class Handler extends ExceptionHandler { public function register(): void { $this->renderable(function (EntityNotFoundException $e, Request $request) { return ApiProblem::response($e->getMessage(), 404); }); } }
归属
此存储库的大部分内容是从 Laminas API Tools 复制的。我想提供一个针对 Laravel 的简化接口。虽然可以直接从 Laminas 库中使用此工具,但它将附带大量开销。