siganushka/api-client

dev-main 2022-06-30 08:18 UTC

This package is auto-updated.

Last update: 2022-06-30 08:18:40 UTC


README

An API Client Abstraction Layer.

Installation

$ composer require siganushka/api-client dev-main

Usage

An abstract class needs to implement 3 methods:

// Configure the options required for the request
AbstractRequest::configureOptions(OptionsResolver $resolver): void;

// Configure the request with resolved options
AbstractRequest::configureRequest(RequestOptions $request, array $options): void;

// Parse the response data (ParseResponseException when there is an error)
AbstractRequest::parseResponse(ResponseInterface $response);

Github get a user example:

https://docs.github.com/cn/rest/users/users#get-a-user

namespace App\Request;

use Siganushka\ApiClient\AbstractRequest;
use Siganushka\ApiClient\RequestOptions;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\HttpClient\ResponseInterface;

class GithubUsers extends AbstractRequest
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setRequired('username');
        $resolver->setAllowedTypes('username', 'string');
    }

    protected function configureRequest(RequestOptions $request, array $options): void
    {
        $request
            ->setMethod('GET')
            ->setUrl(sprintf('https://api.github.com/users/%s', $options['username']))
        ;
    }

    protected function parseResponse(ResponseInterface $response): array
    {
        return $response->toArray();
    }
}

Implementation