tripsy/api-wrapper

API响应包装器

v1.0 2024-04-22 14:31 UTC

This package is auto-updated.

Last update: 2024-09-22 15:46:30 UTC


README

此包装器可用于构建请求、处理响应,并为REST API创建标准响应。

响应将包含以下键

  • success
    • 如果没有遇到错误,返回 true
  • message
    • 返回一个描述响应的 string 消息
  • errors
    • 返回一个包含遇到错误的详细列表的 array
  • data @return mixed
    • 返回包含响应相关数据的 arraystring
  • meta @return array
    • 可选的额外信息可以作为键/值对的 array 返回

需求

此包是为了在Laravel中使用而构建的,但它没有强依赖。

此包假设请求是通过 lluminate\Support\Facades\Http 发出的

推荐

  • php ^7.3
  • laravel/framework ^8

安装

使用Composer安装此包

  composer require tripsy/api-wrapper

示例

输出响应

use Tripsy\ApiWrapper\ApiWrapper;

function index(ApiWrapper $apiWrapper): JsonResponse {
    $results = [];

    $apiWrapper->success(true);
    $apiWrapper->message(__('message.success'));
    $apiWrapper->data([
        'results' => $results,
        'count' => count($results),
    ]);

    return response()->json($apiWrapper->resultArray(), Response::HTTP_OK);
}

POST请求

use Tripsy\ApiWrapper\ApiWrapper;

function store(ApiWrapper $apiWrapper): string
{
    $apiWrapper->requestMethod('POST');
    $apiWrapper->requestUrl('https://request.url');

    $validate = true;

    if ($validate === false) {
        // the next line of code is not mandatory
        // by default value for `success` is false anyway
        $apiWrapper->success(false);

        $apiWrapper->message(__('message.error'));

        $apiWrapper->errors([
            'Sample error',
            'Another sample error',
        ]);

        $apiWrapper->pushMeta('source', 'my_method');
        $apiWrapper->pushMeta('reference', 'my_app');
    } else {
        $apiWrapper->requestParams([
            'name' => 'John',
            'age' => '34',
            'gender' => 'male',
        ]);

        $apiWrapper->requestHeaders('X_FORWARDED_FOR', '127.0.0.1');

        $apiWrapper->makeRequest(function () use ($apiWrapper) {
            return Http::asForm()
                ->withHeaders($apiWrapper->requestHeaders())
                ->withOptions([
                    'verify' => true,
                ])
                ->timeout(120)
                ->post($apiWrapper->requestUrl(), $apiWrapper->requestParams());
        });

        // `success` will be set as true within `makeRequest` to reflect if the API response status code was between 200 & 300
        if ($apiWrapper->success() === true) {
            $apiWrapper->data(json_decode($apiWrapper->data(), true));

            //handle `result`
            switch ($apiWrapper->getData('result')) {
                case 'success':
                    $apiWrapper->pushMeta('happy', 'yes');
                    break;
                case 'failed':
                    // since the API request was a success but didn't returned the expected result
                    $apiWrapper->success(false);

                    $apiWrapper->pushMeta('happy', 'no');

                    $apiWrapper->message(__('message.failed'));
                    break;
                default:
                    $apiWrapper->pushMeta('happy', '?');

                    $apiWrapper->success(false);
                    $apiWrapper->message(__('message.result_not_defined'));
                    break;
            }
        }
    }

    return $apiWrapper->resultJson();
}

另一个POST请求

use Tripsy\ApiWrapper\ApiWrapper;

function query(ApiWrapper $apiWrapper): array
{
    $apiWrapper->requestMethod('POST');
    $apiWrapper->requestUrl('https://request.url');
    $apiWrapper->requestHeaders('Content-Type', 'application/json');
    $apiWrapper->requestHeaders('Accept', 'application/json');
    $apiWrapper->requestParams([
        'formData' => [
            'name' => 'John',
            'age' => '34',
            'gender' => 'male',
        ],
        'sourceData' => [
            'website' => config('app.url'),
            'environment' => config('app.env'),
            'ipAddress' => '127.0.0.1',
        ],
    ]);

    //$apiWrapper->debug(true);
    $apiWrapper->makeRequest(function () use ($apiWrapper) {
        return Http::withToken('your_secret_token')
            ->withHeaders($apiWrapper->requestHeaders())
            ->withOptions([
                'verify' => true,
            ])
            ->post($apiWrapper->requestUrl(), $apiWrapper->requestParams());
    });

    $responseType = $apiWrapper->getMeta('responseType');

    if (config('app.env') == 'production') {
        if ($responseType == 'hidden') {
            return [];
        }
    }

    return $apiWrapper->resultArray();
}

GET请求

use Tripsy\ApiWrapper\ApiWrapper;

function query(ApiWrapper $apiWrapper): array
{
    $ipAddress = '192.168.0.1';

    $apiWrapper->requestMethod('GET');
    $apiWrapper->requestUrl('https://request.url/location/'.urlencode($ipAddress));
    $apiWrapper->requestHeaders('Accept', 'application/json');

    $apiWrapper->makeRequest(function () use ($apiWrapper) {
        return Http::withToken('your_secret_token')
            ->withHeaders($apiWrapper->requestHeaders())
            ->withOptions([
                'verify' => true,
            ])
            ->get($apiWrapper->requestUrl(), $apiWrapper->requestParams());
    });

    if ($apiWrapper->success() === false) {
        Log::channel('test')->info($apiWrapper->message());
    }
}