adamculp / api-consumer
处理 REST API 的基本 API 包装器。
1.0.0
2013-04-12 18:33 UTC
Requires
- php: >=5.3.0
This package is auto-updated.
Last update: 2024-08-24 13:05:24 UTC
README
关于
一个简单的 PHP 7.3 类,用于通过 GET 使用 Curl 消费 API。(创建用于消费 API,也可用于其他用途)方法构建 API URL 参数、连接 URL 并解析预期的 JSON 响应。
将来我打算添加返回 XML 的可能性,甚至可能将有限的 Curl 功能拆分到另一个类中,或者简单地使用 Guzzle。
要求
如果需要命名空间,则需要 PHP 版本 7.3。
安装
可以直接从 GIT 克隆使用此类。
git clone https://github.com/adamculp/api-consumer.git
您还可以下载 ApiConsumer 包并将其移动到您想要的位置,然后您的脚本可以调用它。
或者,您也可以简单地复制 ApiConsumer.php 文件到您想要的位置,并以这种方式调用它。
非 Composer 使用
此类使用 PHP 5.3+ 可用的命名空间编写,如果不做修改,则将按以下方式使用:注意:此类包含利用 Active.com 的特定 Mashery API 所需的信息,但您可以更改 URL 和参数以适应其他返回 JSON 的 API。
require_once 'path/to/src/ApiConsumer/Consumer.php';
use ApiConsumer\Consumer;
$apiConsumer = new Consumer();
$url = 'http://api.amp.active.com/search?';
$apiConsumer->setUrl($url);
$meta = 'meta:channel=Running+meta:startDate:daterange:today..' . date('Y-m-d', strtotime('next month'));
$params = array(
'k' => 'ultra+marathon',
'v' => 'json',
'l' => 'Florida',
'r' => '25',
's' => 'date_asc',
'api_key' => '{Add API Key Here}',
'm' => $meta
);
$options = array(); // key=>value pairs can be added here to alter the curl call
$apiConsumer->setParams($params);
$apiConsumer->setOptions($options);
$apiConsumer->setResponseType('json');
$apiConsumer->setCallType('get');
$result = $apiConsumer->doApiCall();
Composer 使用
使用 https://getcomposer.org.cn 中显示的两种方法之一安装 Composer 后,composer.json 将如下所示
{
"require": {
"adamculp/api-consumer": "dev-master"
}
}
然后您需要更改上面的 require_once 以指向 Composer 自动加载,而不是指向类本身。
require_once 'vendor/autoload.php'; // to include the composer autoloader
从那里您可以使用您喜欢的 $result 数组。
请使用 /api-consumer/index.php 作为如何包含和使用类的示例(不包括 API 密钥)。