negartarh/apiwrapper

为 Laravel API 响应提供超快速、轻量级、标准、Octane 兼容和高可定制的包

v0.7.6 2024-04-13 04:02 UTC

This package is auto-updated.

Last update: 2024-09-08 11:15:06 UTC


README

Laravel 缺失 API 响应包装器 GitHub Repo stars

超快速 | 轻量级 | 标准 | Octane 兼容 | 高可定制

适用于从小型到大型规模的应用程序

Static Badge Static Badge Static Badge GitHub License GitHub Release Packagist Downloads

GitHub commit activity GitHub code size in bytes GitHub repo file or directory count GitHub Discussions Languages



简介

Laravel 缺失 API 响应包装器是一个高质量和标准化的包,使得在 Laravel 中创建和管理标准 API 响应变得简单。此包既快速又轻量,完全兼容 Laravel Octane,高度可定制,并自动启用所有 API 响应的标准化。使用此包,您可以轻松管理错误并开发符合 HTTP 和 REST 标准的自动提供响应的标准 API 服务。

此包可在任何地方使用,从验证器到控制器和其他组件,并自动提供请求状态、消息、错误和执行时间等功能。此外,向响应添加自定义值或禁用这些功能也非常容易。

使用此包保证 API 响应的标准化,这意味着您可以持续稳定地提供高质量、易于理解和使用的响应,同时完全符合标准。所有这些操作都是自动完成的。

安装

要安装 Laravel 缺失 API 响应包装器,只需运行以下命令

composer require negartarah/apiwrapper

配置

安装包后,您需要发布其配置文件。为此,请运行以下命令

php artisan vendor:publish --provider="Negartarh\APIWrapper\APIResponseServiceProvider"

这会将配置文件 apiwrapper.php 发布到您的配置目录,并将本地化文件发布到 languages/vendor/apiwrapper 目录。

基本用法

有两种方式可以使用此包:使用外观或使用辅助函数。无论哪种方式,您都会得到相同的结果,完全取决于您。

外观

示例 1。

use Negartarh\APIWrapper\Facades\APIResponse;

...

public function index():\Illuminate\Http\Response
{
    $users = User::latest()->take(10)->get();
    
    # Alias of
    # return APIResponse::success($users);
    return APIResponse::ok($users);
}

辅助函数

示例 1。

use Negartarh\APIWrapper\Facades\APIResponse;

...

public function index():\Illuminate\Http\Response
{
    $users = User::latest()->take(10)->get();
    
    return apiwrapper()->ok($users);
    # or
    return api_response()->ok($users);
}

上述代码的结果如下

{
  "status": 200, // HTTP status code
  "message": "OK", // HTTP message
  "data": [ // Response data
    {
      "id": 1,
      ...
    },
    ...
  ],
  "errors": [], // Errors
  "execution": "13ms", // Serverside exection time
  "version": "3.2.0" // Your application version
}

如您所见,简单的输出信息已自动替换为适合 API 请求的分类信息。看看输出键,它们都是可更改和可编辑的,但在那之前,最好先对包进行更多研究,并熟悉其更多功能。

高级用法

基于 HTTP 标准的自动输出

示例 1. 存储数据

use Illuminate\Support\Facades\Request;
use Negartarh\APIWrapper\Facades\APIResponse;

...

public function create(Request $request):\Illuminate\Http\Response
{
    $user = User::where('email', '=', $request->get('email'))
                  ->firstOrCreate();
                  
    return APIResponse::created($user);
}

上述代码的结果如下

{
  "status": 201, // HTTP status code
  "message": "Created", // HTTP message
  "data": { // Response data
    "id": 1,
    ...
  },
  "errors": [], // Errors
  "execution": "10ms", // Serverside exection time
  "version": "3.2.0" // Your application version
}

示例 2. 无内容

use Illuminate\Support\Facades\Request;
use Negartarh\APIWrapper\Facades\APIResponse;

...

public function index(Request $request):\Illuminate\Http\Response
{
    $posts = Post::all();
    
    if(!is_countable($posts) or count($posts) == 0):
                 
        return APIResponse::noContent();
        
    else:
        ...
}

上述代码的结果如下

{
  "status": 204, // HTTP status code
  "message": "No Content", // HTTP message
  "data": [],
  "errors": [],
  "execution": "10ms",
  "version": "3.2.0"
}

示例 3. 验证数据

use Illuminate\Http\Exceptions\HttpResponseException;
use Negartarh\APIWrapper\Facades\APIResponse;

class ExampleCaptchaRequest extends FormRequest // example rule class
{
    ...

    /**
     * Handle a failed validation attempt.
     *
     * @param Validator $validator
     * @return HttpResponseException
     */
    public function failedValidation(Validator $validator): HttpResponseException
    {
        # based on RFC: 4918
        return APIResponse::unprocessableEntity($validator->errors());
    }
}

上述代码的结果如下

{
  "status": 422, // HTTP status code
  "message": "Unprocessable Entity", // HTTP message
  "errors": {
    "captcha": [
      "The CAPTCHA has expired."
    ]
  },
  "data": [],
  "execution": "41ms",
  "version": "3.2.0"
}

让我们也看看服务器响应和输出头:

plot plot 一切看起来都很不错。如果您难以记住 HTTP 标准没有问题,注意下一个示例。

替代方法

示例 1. 状态方法

use Illuminate\Http\Exceptions\HttpResponseException;
use Negartarh\APIWrapper\Facades\APIResponse;

class ExampleCaptchaRequest extends FormRequest // example rule class
{
    ...

    /**
     * Handle a failed validation attempt.
     *
     * @param Validator $validator
     * @return HttpResponseException
     */
    public function failedValidation(Validator $validator): HttpResponseException
    {
        return APIResponse::status(413, $validator->errors());
    }
}

结果是

{
  "status": 413,
  "message": "Request Entity Too Large",
  "errors": [
    ...
  ],
  "data": [],
  "execution": "17ms",
  "version": "3.2.0"
}

请稍等,自定义输出信息不是更好吗?所以请注意以下示例

自定义信息

示例 1。

use Illuminate\Http\Exceptions\HttpResponseException;
use Negartarh\APIWrapper\Facades\APIResponse;

class ExampleAuthenticationRequest extends FormRequest // example rule class
{
    ...

    /**
     * Handle a failed validation attempt.
     *
     * @param Validator $validator
     * @return HttpResponseException
     */
    public function failedValidation(Validator $validator): HttpResponseException
    {
        # Alias of
        # return APIResponse::status(403, $validator->errors(), 'Where are you looking here?');
        retun APIResponse::forbidden($validator->errors(), 'What are you looking for here?');

    }
}

并猜测结果

{
  "status": 403,
  "message": "What are you looking for here?",
  "errors": {
    ...
  },
  "data": [],
  "execution": "15ms",
  "version": "3.2.0"
}

但是等等,还有一个更好的解决方案,为什么不实现我们自己的团队标准呢?要做到这一点,只需将您的标准添加到项目中config文件夹的apiwrapper.php文件中,或根据需要对其进行更改。

自定义方法

示例 1。

# path/to/project/configuration/dir/apiwrapper.php

return [
    ...
    'methods' => [
        ...
        'accessDenied' => [
            'code' => 403,
            'message' => 'What are you looking for here?',
            'headers' => [
                'Authorization' => 'Failed',
            ],
        ],

并在您的项目中轻松使用定义的方法。

use Illuminate\Support\Facades\Request;
use Negartarh\APIWrapper\Facades\APIResponse;

...

public function login(Request $request):\Illuminate\Http\Response
{
    $user = User::where('access_token', '=', $request->get('access_token'))
                  ->first();
                  
    if($user == null):
        return APIResponse::accessDenied();
    else:
        ...
}

如果您注意到了上面的示例,您会看到每个状态的头信息都是可调整的,但是在运行时如何调整它呢?要做到这一点,请注意以下示例

可调整的头信息

示例 1。

use Illuminate\Support\Facades\Request;
use Negartarh\APIWrapper\Facades\APIResponse;

...

public function login(Request $request):\Illuminate\Http\Response
{
    $user = User::where('access_token', '=', $request->get('access_token'))
                  ->first();
                  
    if($user == null):
        return APIResponse::accessDenied($user, headers: [
                    ...
               ]);
        # or 
        return APIResponse::accessDenied($user)
               ->withHeaders([ ... ]);
    else:
        ...
}

本地化

如果您的API是多语言的,此包是可翻译的,并且已被翻译成波斯语阿拉伯语土耳其语。要使用翻译,请参考Laravel文档以获取更多信息,请注意以下示例

示例 1. 本地化响应

use Negartarh\APIWrapper\Facades\APIResponse;

...
App::setLocale('fa');
...

return APIResponse::insufficientStorage();

以及结果

{
  "status": 507,
  "message": "فضای ذخیره سازی ناکافی",
  ...
}

如果您不需要翻译信息,您可以通过配置文件来禁用它。

示例 2. 禁用本地化

# path/to/project/configuration/dir/apiwrapper.php

return [
    ...
    'localization' => false,

排序响应

如果您希望进一步标准化您的响应,可以按字母顺序排序。您可以通过在配置文件中使用'sort'键来实现这一点。通过将此键设置为true,您的响应将按字母顺序排序。此选项的默认状态为false。

示例 1. 启用排序响应

# path/to/project/configuration/dir/apiwrapper.php

return [
    ...
    'sort' => true,

自定义响应

要启用、禁用或自定义响应中的默认键,只需通过配置文件进行操作。

示例 1. 禁用默认键

# path/to/project/configuration/dir/apiwrapper.php

return [
    ...
    'fields' => [
        ...
        'execution' => false,

示例 2. 改变算法

# path/to/project/configuration/dir/apiwrapper.php

return [
    ...
    'fields' => [
        ...
        'version' => fn(mixed $content, int $status, string $message) => env('API_VERSION', 'x.x.x'),
        or
        'version' => 'Namespace\Of\Custom\Class::static_method', //recommended
        or
        'version' => 'any_callable_function',

您可以通过学习配置文件来获取更多关于此的信息。

更改默认键名

与前面的示例类似,要更改响应中的默认键名,只需通过配置文件进行操作。

示例 1。

# path/to/project/configuration/dir/apiwrapper.php

return [
    ...
    'replaces' => [
        ...
        'data' => 'content',

结果

{
  "status": 200,
  "message": "OK",
  "content": [ // changed from data to content
    {
      "id": 1,
      ...
    },
    ...
  ],
  "errors": [],
  "execution": "7ms",
  "version": "3.2.0"
}

添加自定义值

要在API响应中添加自定义值,请在配置文件中执行以下操作。

示例 1。

# path/to/project/configuration/dir/apiwrapper.php

return [
    ...
    'custom_keys'=>[
        'app'=> 'My Wonderful APP',
        ...
        'time'=> fn(mixed $content, int $status, string $message) => \Illuminate\Support\Carbon::now(),
        or
        'time' => 'Namespace\Of\Custom\Class::static_method', //recommended
        or
        'time' => 'any_callable_function',

以及结果

{
  "status": 200,
  ...
  "app": "My Wonderful APP",
  "time": "2024-01-05T02:42:10.636571Z"
}

提示

示例 1. 使用axios进行现实世界软件开发

后端
# API Login Controller
use Negartarh\APIWrapper\Facades\APIResponse;

...

    public function login(LoginRequest $request):\Illuminate\Http\Response
    {
        ...
        
        return APIResponse::ok([
                ...
            ]);
    }

# API LoginRequest Form Request
use Negartarh\APIWrapper\Facades\APIResponse;

...

    public function failedValidation(Validator $validator): HttpResponseException
    {
        return APIResponse::unprocessableEntity($validator->errors());
    }
前端
let isOnRequest = false;

...

async function submitForm() {

    isOnRequest = true;

    await axios.post('api/login', {
        ...
    })
    .then((response) => {
        // if validation passed, you can get response here
        console.log(response.data)
    }).catch((error)=>{
        // if validation failed, you can catch errors here
        console.log(error.response.data)
    }).finally(()=>{
        isOnRequest = false;
    });
}

示例 2. 处理API响应中的404状态

# app/Exceptions/Handler.php

class Handler extends ExceptionHandler
{
    ...
    
        public function register()
        {
            $this->reportable( function ( Throwable $e ) {
                //
            } );
    
            $this->renderable(function (NotFoundHttpException $e, Request $request) {
                if ($request->is('api/*')):
                    return APIResponse::status(404);
                endif;
            });
    
        }

内置方法

下表给出了预定义的方法,包括HTTP代码和信息文本。所有这些值都可以通过配置文件进行访问和更改。

要求

  • php: >= 8.1
  • illuminate/support: *

贡献

如果您能提供PR,我们将非常高兴。

许可

这是一个免费软件包,在MIT许可证下发布。