我尝试使用谷歌搜索,但搜索结果中只有一个已经过期的Yahoo!教程,而且没有任何关于标头等详细信息的介绍。
请问是否有相关的资料可以帮助我学习如何调用REST API或者提供相应的文档?即使在W3schools,他们也只描述了SOAP方法。在PHP中有哪些不同的选项可以用来调用REST API呢?
cURL
扩展访问任何 REST API。但是,API 文档(方法、参数等)必须由你的客户端提供!// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
$response = json_decode($response);
$response = new SimpleXMLElement($response);
file_get_contents
函数会失败,并返回null。如果响应体包含错误消息,你将无法检索到它。 - Bart Verkoeijen使用Guzzle。它是一款“PHP HTTP客户端,使HTTP/1.1易于处理并消除了使用Web服务时的痛点”。使用Guzzle比使用cURL要容易得多。
以下是网站上的一个示例:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody(); // {"type":"User"...'
var_export($res->json()); // Outputs the JSON decoded data
使用Postman,您可以生成调用API的代码,适用于大多数编程语言,包括PHP
。以下是步骤:
步骤1
使用Postman UI指定API调用规范,即URL
、方法
、标头
、参数
、正文
等。
步骤2
在最右侧,有一个小按钮,您可以查看生成的代码。
步骤3
从下拉列表中选择您喜欢的语言(和库),然后就可以开始了!
CURL是最简单的方法。下面是一个简单的调用示例
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "THE URL TO THE SERVICE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
使用HTTPFUL
Httpful是一个简单、可链接、易读的PHP库,旨在使HTTP通信变得合理。它让开发人员专注于与API交互,而不是在curl set_opt页面中筛选;是一个理想的PHP REST客户端。
Httpful包括...
示例:
发送GET请求。获取自动解析为JSON的响应结果。
该库检测到响应中的JSON Content-Type,并自动将响应解析为本机的PHP对象。
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)->send();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
$condition = $response->weather[0]->main;
那样解析JSON,除非我在PHP方面做错了什么。 - weteamsteveGET
或POST
方法,或两种方法都支持。以下代码是我使用的,我正在调用我的自己的Web服务API,因此我已经知道API需要什么以及它将返回什么。它支持GET
和POST
方法,因此敏感度较低的信息进入URL(GET)
,像用户名和密码这样的信息作为POST
变量提交。此外,所有内容都通过HTTPS
连接传输。echo $my_json_variable
使该json字符串对客户端可用。$processed = FALSE;
$ERROR_MESSAGE = '';
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass"); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);
if ($obj->{'code'} == '1')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{'data'};
}
...
if (!$processed && $ERROR_MESSAGE != '') {
echo $ERROR_MESSAGE;
}
顺便提一下,我也尝试过使用file_get_contents()
方法,正如这里的一些用户建议的那样,但对我来说效果不佳。我发现curl
方法更快、更可靠。
// This class has all the necessary code for making API calls thru curl library
class CurlHelper {
// This method will perform an action/method thru HTTP/API calls
// Parameter description:
// Method= POST, PUT, GET etc
// Data= array("param" => "value") ==> index.php?param=value
public static function perform_http_request($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
}
require_once("curl_helper.php");
...
$action = "GET";
$url = "api.server.com/model"
echo "Trying to reach ...";
echo $url;
$parameters = array("param" => "value");
$result = CurlHelper::perform_http_request($action, $url, $parameters);
echo print_r($result)
您可以使用file_get_contents
发出任何http的POST / PUT / DELETE / OPTIONS / HEAD
方法,除了如函数名称所示的GET
方法。
$data
是一个关联数组(data[fieldname] = value),它保存发送到 API 方法的数据。 - Christoph Winklercurl_close
函数,则可能会导致额外的内存消耗。 - Bart Verkoeijenjson_encode($data)
之后,这个问题就只有一次能够解决。 - Neurotransmitter