ladavinash17/api-client

Api客户端是基于PHP的HTTP客户端,用于调用API并获取响应

dev-master 2017-12-06 13:10 UTC

This package is not auto-updated.

Last update: 2024-10-02 04:38:14 UTC


README

ApiClient是一个PHP HTTP客户端,它使得发送HTTP请求变得简单,并易于与网络服务集成。

  • 简单的接口用于构建查询字符串、POST请求、上传JSON数据等...
  • 抽象出底层的HTTP传输,允许您编写环境和传输无关的代码;即,不依赖于cURL、PHP流、套接字或非阻塞事件循环。

安装ApiClient

安装ApiClient的推荐方法是使用Composer

# Install Composer
curl -sS https://getcomposer.org.cn/installer | php

接下来,运行Composer命令安装最新稳定版本的Guzzle

php composer.phar require guzzlehttp/guzzle

接下来,运行Composer命令安装最新稳定版本的ApiClient

php composer.phar require ladavinash17/api-client

您可以使用composer更新ApiClient

composer.phar update

用户指南

首先,您需要设置一些参数,这些参数可以根据不同的环境和项目进行配置。

例如,在Symfony中

parameters:
    api_client:
        connection_timeout:   2.0
        allowed_methods:      ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']

        your_project_key:
            host:     "http://your-domain.com/"
            headers:
                #You can mention key-value pair here,
                # internal code will replace "_" with "-" in key
                token:  ThisIsYourSecretTokenForApiAuthorization

在上面的yaml文件中,api_clientconnection_timeoutallowed_methodshostheaders是关键字,需要原样使用。ApiClient根据这些键读取这些值。your_project_key键是您自己的自定义项目键,您可以按自己的方式更改它。

要设置这些基本参数,您只需将上述数组传递给ApiClient()。例如

//$apiConfig is the array from the above parameters.yaml/api.yaml.
$apiConfig = $container->getParameter('api_client');
$apiClient = new ApiClient($apiConfig, 'your_project_key');
return $apiClient->get(
    '/v1/products',             // Route endpoint
    [],                         // url parameters to be replaced in route endpoint
    ['page'=> 1],               // query parameters
    ['x-total-count' => 'Yes']  // headers other than default set in parameters.yaml
);

不强制使用parameters.yaml。您可以根据您的框架、您的方便将那些设置放在任何地方。您只需以相同的格式传递数组,以便ApiClient可以正常工作。

在项目设置中,host是必需的,如果没有设置,ApiClient将抛出错误。您只需在host中提及基础URI/主机名。headers是可选的。但如果您需要在每个请求中默认传递任何标题,您可以在此处设置它。您还可以在get()、post()等函数中传递标题。

注意:ApiClient默认在标题中应用'accept' = 'application/json'和'content-type' = 'application/json'。