kodepandai/laravel-api-response

laravel的API响应助手。

v1.3.1 2022-12-23 01:55 UTC

This package is auto-updated.

Last update: 2024-09-12 10:15:46 UTC


README

一个辅助包,用于以结构化的方式返回JSON API响应。

默认情况下,响应的结构将如下所示

{
  "success": true, // it was successfull or not
  "title": "Users", // the title/headline/section 
  "message": "Active users only", // the message/description/highlight
  "data": { // if it was successfull
    // profile..
    // users..
    // products..
    // etc..
  },
  "errors": { // if it was not successfull
    // validation errors..
    // any other errors..
  }
}

示例

{
  "success": true,
  "title": "Users",
  "message": "Succesfully create a user",
  "data": {
    "id": 1,
    "name": "John Doe",
    "address": "4th Semarang Raya",
  },
}

安装

$ composer require kodepandai/laravel-api-response:dev-beta

要求

  • PHP ^8.1
  • Laravel ^10.0

Laravel ^11

安装后,在bootstrap/app.php中注册API响应处理程序

use KodePandai\ApiResponse\ApiExceptionHandler;

return Application::configure(basePath: dirname(__DIR__))
    //...
    ->withExceptions(function (Exceptions $exceptions) {
        // dont report any api response exception
        $exceptions->dontReport([
            \KodePandai\ApiResponse\Exceptions\ApiException::class,
            \KodePandai\ApiResponse\Exceptions\ApiValidationException::class,
        ]);
        // api response exception handler for /api
        $exceptions->renderable(function (Throwable $e, Request $request) {
            if ($request->wantsJson() || $request->is('*api*')) {
                return ApiExceptionHandler::render($e, $request);
            }
        });
    });

Laravel ^10

安装后,在app/Exceptions/Handler.php中注册API响应处理程序

use KodePandai\ApiResponse\ApiExceptionHandler;

class Handler extends ExceptionHandler
{
    protected $dontReport = [
        \KodePandai\ApiResponse\Exceptions\ApiException::class,
        \KodePandai\ApiResponse\Exceptions\ApiValidationException::class,
    ];

    public function register()
    {
        $this->renderable(function (Throwable $e, Request $request) {
            if ($request->wantsJson() || $request->is('*api*')) {
                return ApiExceptionHandler::render($e, $request);
            }
        });
    }
}

上述处理程序将自动将任何异常转换为ApiResponse JSON响应。

配置

使用vendor:publish命令发布配置文件

$ php artisan vendor:publish --tag=api-response-config

用法

待办事项

返回响应

待办事项

抛出异常

待办事项

覆盖响应结构

待办事项

开发

  • 要测试,请运行composer test