adiafora/php-api-client

用于通过PHP发送到API的包。

1.3.9 2021-04-04 13:58 UTC

This package is auto-updated.

Last update: 2024-09-04 21:34:52 UTC


README

此包使您能够非常容易地使用GET和POST请求访问任何API。您还可以发送头部和参数。

安装

运行

    composer require "adiafora/php-api-client"

配置

您可以使用全局常量设置curl的参数。

SET_CURLOPT_CONNECTTIMEOUT - 连接时等待的秒数。使用0表示无限等待。默认值为10。SET_CURLOPT_TIMEOUT - 允许cURL函数执行的秒数最大值。默认值为10。

用法

您必须创建一个继承自Adiafora\ApiClient\AbstractApiClient抽象类的类。并定义以下方法

getHeaders() - 返回一个头部数组。

getUrl() - 返回一个字符串,即API URL。

在您的项目中,您必须引用这个继承自Adiafora\ApiClient\AbstractApiClient的类。

访问您的类时,您可以将GET或POST请求类型(默认为GET)和请求参数数组(如果有)传递给构造函数。如果您执行一个不带参数的GET请求,则不需要向构造函数传递任何内容。

 //Example

 $api = new MyApiClient('POST', ['name' => 'Sergey']);
 // or
 $api = new MyApiClient();
 

要向API发出请求,请调用send()方法

 $response = $api->send();

此方法返回一个包含以下方法的Adiafora\ApiClient\ApiResponse类的对象

code() - 返回响应代码。

response() - 使用json_decode()解码从API返回的响应。因为大多数API以json格式返回响应。如果您想以原始形式获取答案,则可以使用dirty()方法。

dirty() - 以原始形式返回答案,不进行转换。

error() - 返回curl的curl_error()

errno() - 返回curl的curl_errno()

requestParameters() - 返回请求参数。

requestUrl() - 返回请求的URL。

requestHeaders() - 返回请求的头部。

totalTime() - 返回上次传输的总交易时间(以秒为单位)。

真实示例

例如,我们需要连接到Yandex.Webmaster API。

更多信息请参阅API文档 https://yandex.com/dev/webmaster/doc/dg/concepts/About.html/

我们创建一个名为WebmasterApiClient的类

    use Adiafora\ApiClient\AbstractApiClient;
    
    class WebmasterApiClient extends AbstractApiClient
    {
        private $resource;    

        private $token;
    
        private $userId;
    
        public function __construct(string $resource, string $method, array $params = [])
        {
            parent::__construct($method, $params);
    
            $this->resource = $resource;
            $this->userId   = USER_ID;
            $this->token    = TOKEN;
        }
    
        public function getHeaders(): array
        {
            return [
                'Authorization: OAuth ' . $this->token,
                'Accept-Language: ru',
                'Content-Type: application/json; charset=utf-8'
            ];
        }
    
        public function getUrl(): string
        {
            return 'https://api.webmaster.yandex.net/v4/user/' . $this->userId . '/' . $this->resource;
        }
    }

我们已经实现了2个必需的方法getHeaders()getUrl()。其余的,包括构造函数的实现,仅用于实现特定的API。

现在我们想要获取所有主机的列表。这很简单!只需

// @see https://yandex.com/dev/webmaster/doc/dg/reference/hosts-docpage/
$api = new WebmasterApiClient('hosts', Adiafora\ApiClient\Method::GET);
$response = $api->send();

$response->code(); // 200
$response->response(); // array()

或使用参数获取SQI更改的历史记录

// @see https://yandex.com/dev/webmaster/doc/dg/reference/sqi-history.html/
$api = new WebmasterApiClient('hosts/' . $hostId . '/sqi-history', Adiafora\ApiClient\Method::GET, [
            'date_from' => '2016-01-01T00:00:00,000+0300',
        ]);
$api->send(); 

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件。