chhw/api-response

此包为您提供了更简单的方式来返回RESTful API响应。

1.3.0 2022-01-20 16:10 UTC

This package is auto-updated.

Last update: 2024-09-21 20:49:13 UTC


README

此包为您提供了更简单的方式来返回RESTful API响应。

安装

通过composer安装

    $ composer require chhw/api-response

如果您使用的是Laravel 5.5,请在下面的config/app.php中添加此代码。

    <?php
        'providers' => [
            CHHW\ApiResponse\ApiResponseServiceProvider::class,
        ],
    ?>

[选项] 获取响应配置来自定义调试信息。

    $ php artisan vendor:publish --provider="CHHW\ApiResponse\ApiResponseServiceProvider"

现在也支持Lumen了!!

bootstrap/app.php中,您应该

  1. 添加$app->register(CHHW\ApiResponse\ApiResponseServiceProvider::class);

[选项] 获取响应配置来自定义调试信息。

    $ cp vendor/chhw/api-response/src/config/response.php config/response.php

用法

应在您的控制器中使用。

定义

您可以选择您喜欢的

  1. 构造函数: $this->response = new ApiResponse
  2. 注入: ApiResponse $response

示例

一般

 // You can set header and option in construct.
$this->response->setHeader(["lang" => "en"])->setOption(JSON_UNESCAPED_UNICODE);

// Basic usage.
return $this->response->success([1, 2])->json();
return $this->response->error("Oh no")->json();

// Custom status and code.
return $this->response->success([1, 2], 201, "code201")->json();
return $this->response->error("Oh no", 501, "code501")->json();

内联

return $this->response->success([1, 2])->setHeader(["lang" => "en"])->setOption(JSON_UNESCAPED_UNICODE)->json();
return $this->response->error("Oh no", 501, "code501")->setHeader(["lang" => "en"])->setOption(JSON_UNESCAPED_UNICODE)->json();

[选项] 自定义调试信息

如果您有自定义代码,默认情况下它将匹配config/response.php的调试信息设置

// Controller
return $this->response->error([1, 2], 500, 'custom500')->json();

// config/response.php
return [
    'code' => [
        'custom500' => 'Internal Server Error',
    ]
];

响应

成功

 {
    "success": true,
    "detail": {
        "status": 200,
        "code": "200",
        "message": "OK"
    },
    "data": {
        ...
    },
    "link": null,
    "meta": null
 }

错误

 {
    "success": false,
    "detail": {
        "status": 404,
        "code": "404",
        "message": "Something went wrong."
    },
    "error": {
        ...
    },
    "link": null,
    "meta": null
 }

支持的方法

$data可以是数组、字符串或对象等。

$code用于想要自定义内部HTTP代码的人。

public function success($data = [], $status = 200, $code = "200");
public function error($data = [], $status = 500, $code = "500");
public function setHeader($headers);
public function setOption($options);

日志跟踪

带有唯一UUID4的响应头:X-Trace-Id

集合分页器

集合分页器的使用就像模型一样!

您可以使用API响应和集合分页器一起使用。

示例

collect([1,2,3,4,5])->paginate(10)
collect([1,2,3,4,5])->simplePaginate(15)

支持的方法

paginate($perPage = 15, $pageName = 'page', $page = null);
simplePaginate($perPage = 15, $pageName = 'page', $page = null);