andrey-helldar/api-response

此包已被废弃,不再维护。作者建议使用 dragon-code/api-response 包。

用于标准化基于 Symfony 应用程序 API 响应的包。

v10.0.0 2022-04-20 23:50 UTC

README

API Response

Stable Version Unstable Version Total Downloads License

用于标准化基于 Symfony 应用程序 API 响应的包。

入门

升级指南

[ 返回顶部 ]

安装

要获取最新版本的 API Response,只需使用 Composer 引入项目

$ composer require dragon-code/api-response

此命令将自动安装适合您环境的包的最新版本。

当然,您也可以手动更新您的 require 块并运行 composer update,如果这样选择的话

{
    "require": {
        "dragon-code/api-response": "^9.1"
    }
}

好了!使用 api_response() 辅助函数。

兼容性表

包版本 PHP 最小版本 Symfony 版本 支持 链接
^9.0 7.2.5 ^4.0, ^5.0, ^6.0 Supported 升级指南
^8.0 7.2.5 ^4.0, ^5.0 Not Supported 升级指南
^7.0 7.2.5 ^4.0, ^5.0 Not Supported 升级指南
^6.0 7.3 ^4.0, ^5.0 Not Supported 升级指南
^5.0 7.1.3 ^4.0, ^5.0 Not Supported ---
^4.4.1 5.6.9 ^3.0, ^4.0, ^5.0 Not Supported ---
^4.0 5.6.9 ^3.0, ^4.0 Not Supported ---

[ 返回顶部 ]

使用

使用 data

使用代码作为 NULL

// php 7.4 and below
return api_response(null, 304);

// php 8.0
return api_response( status_code: 304 );

返回代码 304

{
    "data": null
}

[ 返回顶部 ]

使用默认代码作为整数

return api_response(304);

返回代码 200

{
    "data": 304
}

[ 返回顶部 ]

使用默认代码作为字符串

return api_response('qwerty');

返回代码 200

{
    "data": "qwerty"
}

[ 返回顶部 ]

使用代码作为字符串

return api_response('qwerty', 400);

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": "qwerty"
    }
}

[ 返回顶部 ]

使用代码作为整数

return api_response(304, 400);

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": 304
    }
}

[ 返回顶部 ]

作为数组

$data = [
    [
        'title' => 'Title #1',
        'description' => 'Description #1',
    ],
    [
        'title' => 'Title #2',
        'description' => 'Description #2',
    ],
];

[ 返回顶部 ]

作为错误

return api_response($data, 400);

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": [
            {
                "title": "Title #1",
                "description": "Description #1"
            },
            {
                "title": "Title #2",
                "description": "Description #2"
            }
        ]
    }
}

[ 返回顶部 ]

作为成功

return api_response($data);

返回代码 200

{
    "data": [
        {
            "title": "Title #1",
            "description": "Description #1"
        },
        {
            "title": "Title #2",
            "description": "Description #2"
        }
    ]
}

如果第一个参数是数字,则将按代码解析错误并返回。在其他情况下,将返回传递变量的值。

[ 返回顶部 ]

带有附加内容

// php 7.4 and below
return api_response('title', 200, ['foo' => 'bar']);
// or
return api_response('title', null, ['foo' => 'bar']);

// php 8.0
return api_response('title', with: ['foo' => 'bar']);

返回代码 200

{
    "data": "title",
    "foo": "bar"
}

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": "ok"
    },
    "foo": "bar"
}
return api_response(['data' => 'foo', 'bar' => 'baz']);

返回代码 200

{
    "data": "foo",
    "bar": "baz"
}

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": "foo"
    },
    "bar": "baz"
}

[ 返回顶部 ]

不使用 data 键使用

由于该包的目标是统一所有答案,我们将变量定义移动到了一个静态函数中。因此,例如,要启用或禁用使用 data 键包装内容,您需要调用 wrappedwithoutWrap 方法

use DragonCode\ApiResponse\Services\Response;

Response::withoutWrap();

使用代码和没有 data 键作为 NULL

// php 7.4 and below
return api_response(null, 304);

// php 8.0
return api_response( status_code: 304 );

返回代码 304

[]

[ 返回顶部 ]

使用默认代码和没有 data 键作为整数

return api_response(304, 200);

返回代码 200

304

[ 返回顶部 ]

使用默认代码和没有 data 键作为字符串

return api_response('qwerty', 200);

返回代码 200

"qwerty"

[ 返回顶部 ]

使用代码和没有 data 键作为字符串

return api_response('qwerty', 400);

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": "qwerty"
    }
}

[ 返回顶部 ]

使用代码和没有 data 键作为整数

return api_response(304, 400);

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": 304
    }
}

[ 返回顶部 ]

作为数组且没有 data

$data = [
    [
        'title' => 'Title #1',
        'description' => 'Description #1',
    ],
    [
        'title' => 'Title #2',
        'description' => 'Description #2',
    ],
];

作为错误且没有 data

return api_response($data, 400);

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": [
            {
                "title": "Title #1",
                "description": "Description #1"
            },
            {
                "title": "Title #2",
                "description": "Description #2"
            }
        ]
    }
}

[ 返回顶部 ]

作为成功且没有 data

return api_response($data, 200);
// or
return api_response($data);

返回代码 200

[
    {
        "title": "Title #1",
        "description": "Description #1"
    },
    {
        "title": "Title #2",
        "description": "Description #2"
    }
]

如果第一个参数是数字,则将按代码解析错误并返回。在其他情况下,将返回传递变量的值。

[ 返回顶部 ]

带有额外内容且没有 data

// php 7.4 and below
return api_response('title', 200, ['foo' => 'bar']);

// php 8.0
return api_response('title', with: ['foo' => 'bar']);

返回代码 200

{
    "data": "title",
    "foo": "bar"
}

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": "ok"
    },
    "foo": "bar"
}
return api_response(['data' => 'foo', 'bar' => 'baz']);

返回代码 200

{
    "data": "foo",
    "bar": "baz"
}

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": "foo"
    },
    "bar": "baz"
}

[ 返回顶部 ]

无额外数据

在某些情况下,当返回答案时,您还必须提供额外的数据。例如,堆栈跟踪。

为了防止这些数据在生产响应中出现,您可以在全局设置一个标签来显示或隐藏这些数据

use DragonCode\ApiResponse\Services\Response;

env('APP_DEBUG')
    ? Response::allowWith()
    : Response::withoutWith();

现在所有响应将不包含传递的额外数据。

例如

// php 7.4 and below
return api_response('title', 200, ['foo' => 'bar']);
// or
return api_response('title', null, ['foo' => 'bar']);

// php 8.0
return api_response('title', with: ['foo' => 'bar']);

返回代码 200

{
    "data": "title"
}

返回代码 400

{
    "error": {
        "type": "Exception",
        "data": "ok"
    }
}

服务器错误

注意:$with 参数还负责显示服务器端错误消息。

在这种情况下,HTTP 错误将无遮盖地显示。

例如

use DragonCode\ApiResponse\Services\Response;

Response::allowWith();

$e = new Exception('Foo', 0);

return api_response($e);

返回代码 500

{
    "error": {
        "type": "Exception",
        "data": "Foo"
    }
}

use DragonCode\ApiResponse\Services\Response;

Response::withoutWith();

$e = new Exception('Foo', 0);

return api_response($e);

返回代码 500

{
    "error": {
        "type": "Exception",
        "data": "Whoops! Something went wrong."
    }
}

如果代码 >=400 且 < 500,则返回

{
    "error": {
        "type": "Exception",
        "data": "Foo"
    }
}

[ 返回顶部 ]

返回异常实例

class FooException extends \Exception
{
    public function __construct()
    {
        parent::__construct('Foo', 405);
    }
}

class BarException extends \Exception
{
    public function __construct()
    {
        parent::__construct('Bar');
    }
}

$foo = new FooException();
$bar = new BarException();
return api_response($foo);

返回代码 405

{
    "error": {
        "type": "FooException",
        "data": "Foo"
    }
}
return api_response($foo, 408);

返回代码 408

{
    "error": {
        "type": "FooException",
        "data": "Foo"
    }
}
return api_response($bar);

返回代码 400

{
    "error": {
        "type": "BarException",
        "data": "Bar"
    }
}
return api_response($bar, 408);

返回代码 408

{
    "error": {
        "type": "BarException",
        "data": "Bar"
    }
}

您也可以添加额外的数据

return api_response($foo, 405, ['foo' => 'Bar']);
// or
return api_response($foo, 0, ['foo' => 'Bar']);

返回代码 405

{
    "error": {
        "type": "FooException",
        "data": "Foo"
    },
    "foo": "Bar"
}

[ 返回顶部 ]

在 Laravel 和 Lumen 框架中使用最佳实践

如果您使用 Laravel 或 Lumen 框架,您可以根据您的应用程序版本和需求在 app\Exceptions\Handler.php 文件中更新 extends

版本 \ 类型 API + WEB 仅 API
9.x DragonCode\ApiResponse\Exceptions\Laravel\Nine\Handler as ExceptionHandler DragonCode\ApiResponse\Exceptions\Laravel\Nine\ApiHandler as ExceptionHandler
8.x DragonCode\ApiResponse\Exceptions\Laravel\Eight\Handler as ExceptionHandler DragonCode\ApiResponse\Exceptions\Laravel\Eight\ApiHandler as ExceptionHandler
7.x DragonCode\ApiResponse\Exceptions\Laravel\Seven\Handler as ExceptionHandler DragonCode\ApiResponse\Exceptions\Laravel\Seven\ApiHandler as ExceptionHandler

如果您未向此文件添加任何内容,则删除所有属性和方法。

例如,因此,一个干净的文件将看起来像这样

<?php

namespace App\Exceptions;

use DragonCode\ApiResponse\Exceptions\Laravel\Nine\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    //
}

更多示例

<?php

namespace App\Exceptions;

// use DragonCode\ApiResponse\Exceptions\Laravel\Nine\Handler as ExceptionHandler;
use DragonCode\ApiResponse\Exceptions\Laravel\Nine\ApiHandler as ExceptionHandler;

// use DragonCode\ApiResponse\Exceptions\Laravel\Eight\Handler as ExceptionHandler;
// use DragonCode\ApiResponse\Exceptions\Laravel\Eight\ApiHandler as ExceptionHandler;

// use DragonCode\ApiResponse\Exceptions\Laravel\Seven\Handler as ExceptionHandler;
// use DragonCode\ApiResponse\Exceptions\Laravel\Seven\ApiHandler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    //
}

[ 返回顶部 ]

JSON资源

现在,如果您传递资源对象或验证器对象,它也会被美观地渲染

use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin \Tests\Fixtures\Laravel\Model */
final class Resource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'foo' => $this->foo,
            'bar' => $this->bar,
        ];
    }

    public function with($request)
    {
        return ['baz' => 'Baz'];
    }
}
$model = Model::first();
$resource = MyResource::make($model);

return api_response($resource);

返回代码 200

{
    "data": {
        "foo": "Foo",
        "bar": "Bar"
    },
    "baz": "Baz"
}

如果 Response::withoutWrap()

{
    "foo": "Foo",
    "bar": "Bar",
    "baz": "Baz"
}

如果 Response::withoutWith()

{
    "data": {
        "foo": "Foo",
        "bar": "Bar"
    }
}

如果 Response::withoutWith()Response::withoutWrap()

{
    "foo": "Foo",
    "bar": "Bar"
}

[ 返回顶部 ]

验证

$data = [
    'foo' => 'Foo',
    'bar' => 123,
    'baz' => 'https://foo.example'
];

$rules = [
    'foo' => ['required'],
    'bar' => ['integer'],
    'baz' => ['sometimes', 'url'],
];
$validator = Validator::make($data, $rules);

return $validator->fails()
    ? new ValidationException($validator)
    : $validator->validated();

如果成功

{
    "data": {
        "foo": "Foo",
        "bar": 123,
        "baz": "https://foo.example"
    }
}

如果失败

{
    "error": {
        "type": "ValidationException",
        "data": {
            "foo": ["The foo field is required."],
            "bar": ["The bar must be an integer."],
            "baz": ["The baz format is invalid."]
        }
    }
}

[ 返回顶部 ]

许可证

本软件包遵循MIT许可证

[ 返回顶部 ]