i3rror/lapi-response

laravel 的 API 响应特性

v1.2.0 2024-08-19 23:02 UTC

README

Latest Version GitHub repo size GitHub Packagist Downloads

此包可以返回各种 API 响应

如何使用此包

composer require i3rror/LAPI-response

然后将其服务提供者包含到您的 config/app.php 文件中

MA\LaravelApiResponse\Providers\APIResponseProvider::class

之后,您可以发布配置。

php artisan vendor:publish --provider="MA\LaravelApiResponse\Providers\APIResponseProvider" --tag="lapi-response"

然后完成!

为了使用此包,您需要在控制器中包含以下代码

use APIResponseTrait;

有两种使用此包的方法

  1. 通过在 App\Http\Controllers\Controller.php 中添加以下代码来全局使用
  2. 通过在要使用它的控制器中添加以下使用代码来内部使用

以下是几个简短的示例,展示了您可以做什么

use MA\LaravelApiResponse\Traits\APIResponseTrait;

class TestController extends Controller
{
    use APIResponseTrait;
    
    public function index()
    {
        return $this->apiResponse([
            'message' => 'Test Message',
            'data' => [
                [
                    'id' => 1,
                    'name' => 'Test Name',
                ],
                [
                    'id' => 2,
                    'name' => 'Test Name 2',
                ],
                [
                    'id' => 3,
                    'name' => 'Test Name 3',
                ],
            ]
        ]);
    }
}

预期响应

{
  "status": true,
  "statusCode": 200,
  "timestamp": 1662070087,
  "message": "Test Message",
  "data": [
    {
      "id": 1,
      "name": "Test Name"
    },
    {
      "id": 2,
      "name": "Test Name 2"
    },
    {
      "id": 3,
      "name": "Test Name 3"
    }
  ]
}

您可以使用简短的参数值(如果是字符串,则将其设置为消息,如果是数组,则将其设置为数据)消息

return $this->apiOk("test message");

// Or

return $this->apiResponse("test message");

响应

{
  "status": true,
  "statusCode": 200,
  "timestamp": 1662104853,
  "message": "OK",
  "data": "test message"
}

数据

return $this->apiOk([
    [
        'id' => 1,
        'name' => 'Test Name',
    ],
    [
        'id' => 2,
        'name' => 'Test Name 2',
    ],
    [
        'id' => 3,
        'name' => 'Test Name 3',
    ],
]);

// Or

return $this->apiResponse([
    [
        'id' => 1,
        'name' => 'Test Name',
    ],
    [
        'id' => 2,
        'name' => 'Test Name 2',
    ],
    [
        'id' => 3,
        'name' => 'Test Name 3',
    ],
]);

响应

{
  "status": true,
  "statusCode": 200,
  "timestamp": 1662105038,
  "message": "OK",
  "data": [
    {
      "id": 1,
      "name": "Test Name"
    },
    {
      "id": 2,
      "name": "Test Name 2"
    },
    {
      "id": 3,
      "name": "Test Name 3"
    }
  ]
}

还有更多类型,如未找到异常

return $this->apiResponse([
    'type' => 'notfound', // 'type' => 404,
]);
  • 您还可以在单词之间添加短横线,例如 not-found
  • 或者甚至写入 状态码为 404

响应

{
  "status": false,
  "statusCode": 404,
  "timestamp": 1662121027,
  "message": "Not found!",
  "data": null
}

以下是可以使用的所有状态字符串列表 (否则您可以使用状态码)

  • created
  • accepted
  • notfound
  • conflict
  • badrequest
  • exception
  • unauthenticated
  • unauthorized
  • ok

这些都是您可以在 apiResponse 函数中发送的参数

  1. type => 我们之前写的类型。
  2. filter_data => 布尔值。
  3. throw_exception => 布尔值。
  4. message => 字符串。
  5. errorCode => 检查 MA\LaravelApiResponse\Enums\ErrorCodesEnum,您可以将其发送为整数、字符串或 UnitEnum。
  6. status_code => 整数(只有当未发送类型时才会应用)。

示例

/*
* Error code examples:
* THROTTLING_ERROR
* 1021
* ErrorCodesEnum::THROTTLING_ERROR
* ErrorCodesEnum::THROTTLING_ERROR->name
* ErrorCodesEnum::THROTTLING_ERROR->value
*/
return $this->apiResponse([
    'type' => 'notfound',
    'filter_data' => true,
    'throw_exception' => true,
    'message' => 'TestMessage',
    'errorCode' => 'INVALID_CREDENTIALS', // you can make it string, integer or UnitEnum
]);

响应

{
  "status": false,
  "statusCode": 404,
  "timestamp": 1724082523,
  "message": "TestMessage",
  "data": null,
  "errorCode": "INVALID_CREDENTIALS"
}

以下是一个验证函数的示例

$data = $this->apiValidate($request, [
    'countryId' => ['required'],
    'email' => ['required', 'email']
]);

请注意,您可以传递 Illuminate\Http\RequestArray 作为第一个参数

响应

{
  "status": false,
  "statusCode": 400,
  "timestamp": 1662122013,
  "message": "Bad Request!",
  "data": null,
  "errors": [
    {
      "countryId": [
        "The country id field is required."
      ],
      "email": [
        "The email must be a valid email address."
      ]
    }
  ]
}

以下是一个分页响应的示例

$tests = Tests::query()
        ->where('is_active', true)
        ->paginate(2);
        
return $this->apiPaginateResponse($tests);

响应

{
  "status": true,
  "statusCode": 200,
  "timestamp": 1662070940,
  "message": "OK",
  "data": [
    {
      "id": 1,
      "name": "Test 1",
      "is_active": true,
      "created_at": null,
      "updated_at": null
    },
    {
      "id": 2,
      "name": "Test 2",
      "is_active": true,
      "created_at": null,
      "updated_at": null
    }
  ],
  "pagination": {
    "meta": {
      "page": {
        "current": 1,
        "first": 1,
        "last": 10,
        "next": 2,
        "previous": null,
        "per": 2,
        "from": 1,
        "to": 2,
        "count": 2,
        "total": 20,
        "isFirst": true,
        "isLast": false,
        "isNext": true,
        "isPrevious": false
      }
    },
    "links": {
      "path": "https://laravel-v8.test/api/data",
      "first": "https://laravel-v8.test/api/data?page=1",
      "next": "https://laravel-v8.test/api/data?page=2",
      "previous": null,
      "last": "https://laravel-v8.test/api/data?page=10"
    }
  }
}

所有可用的方法列表

$this->apiPaginate($pagination, bool $reverse_data = false)

第一个参数是分页模型,第二个参数是是否反转数据或保持其顺序。

$this->apiException($errors = null, bool $throw_exception = true, $errorCode = null)
$this->apiNotFound($errors = null, bool $throw_exception = true, $errorCode = null)
$this->apiBadRequest($errors = null, bool $throw_exception = true, $errorCode = null)
  1. 第一个参数用于错误,可以设置为字符串或数组。
  2. 第二个参数确定是否抛出异常,默认为 true。
  3. 第三个参数用于随响应返回的错误代码,可以是整数、字符串、null 或 UnitEnum 实例。

重要
如果错误代码设置为 null,则如果配置 returnDefaultErrorCodes 设置为 true,则将返回默认错误代码。

返回 API 禁止错误

第一个参数是消息,可以设置为 null,第二个参数是错误,可以是数组、字符串或 null。

  1. 第一个参数是消息,可以设置为字符串或 null。
  2. 第二个参数是错误,可以设置为字符串或数组。
  3. 第三个参数用于随响应返回的错误代码,可以是整数、字符串、null 或 UnitEnum 实例。

默认消息是 禁止访问

PS:如果错误为 null,则不会在响应中显示错误属性

return $this->apiForbidden('TEST MESSAGE', [
            'error_1' => 'asdasasdasd',
            'error_2' => 'asdasdasdasd'
        ], 'FORBIDDEN');

响应

{
  "status": false,
  "statusCode": 403,
  "timestamp": 1723864903,
  "message": "TEST MESSAGE",
  "data": null,
  "errorCode": "FORBIDDEN",
  "errors": {
    "error_1": "asdasasdasd",
    "error_2": "asdasdasdasd"
  }
}

返回 API 未认证错误

第一个参数是消息,可以设置为 null,第二个参数是错误,可以是数组、字符串或 null。

默认消息是 未认证

PS:如果错误为 null,则不会在响应中显示错误属性

return $this->apiUnauthenticated('TEST MESSAGE', [
            'error_1' => 'asdasasdasd',
            'error_2' => 'asdasdasdasd'
        ], 'UNAUTHORIZED_ACCESS');

响应

{
  "status": false,
  "statusCode": 403,
  "timestamp": 1723864903,
  "message": "TEST MESSAGE",
  "data": null,
  "errorCode": "UNAUTHORIZED_ACCESS",
  "errors": {
    "error_1": "asdasasdasd",
    "error_2": "asdasdasdasd"
  }
}

存在 API 验证

$this->apiValidate($data, $roles, array $messages = [], array $customAttributes = [])

与 Laravel This->validate() 方法的第一个参数相同,第一个参数是数据,第二个参数是角色,第三个参数是消息,最后一个参数是自定义属性。如果通过,则应返回验证数据的值;如果失败,则将抛出使用此特性的异常。

存在 dies 和 dump 数据方法

return $this->apiDD([
    [
        'id' => 1,
        'name' => 'Test Name',
    ],
    [
        'id' => 2,
        'name' => 'Test Name 2',
    ],
    [
        'id' => 3,
        'name' => 'Test Name 3',
    ],
]);

响应

{
  "status": false,
  "statusCode": 422,
  "timestamp": 1662105345,
  "message": "Die and dump",
  "data": [
    {
      "id": 1,
      "name": "Test Name"
    },
    {
      "id": 2,
      "name": "Test Name 2"
    },
    {
      "id": 3,
      "name": "Test Name 3"
    }
  ]
}

配置文件中的错误代码

  1. 启用或禁用它。
  2. 设置错误代码枚举类或可能的自定义枚举类。
  3. 设置错误代码输出类型(字符串或整数)。
  4. 如果设置为 null,则启用或禁用返回默认错误代码。
  5. 为错误函数设置错误代码默认值。

为了发布 ErrorCodesEnum 类

php artisan lapi-response:publish-error-codes

如果需要,也可以指定类名

php artisan lapi-response:publish-error-codes CustomErrorCodesEnum

否则,将使用默认类名 ErrorCodesEnum 生成它

贡献者

许可协议

MIT 许可协议(MIT)。请参阅 许可文件 获取更多信息。