我们的客户端给了我一个REST API,我需要对它进行PHP调用。但事实上,API提供的文档非常有限,所以我真的不知道如何调用该服务。
我试着谷歌它,但唯一出现的是一个已经过期的雅虎!关于如何调用服务的教程。不要提及标题或任何深入的信息。
是否有关于如何调用REST API的适当信息或相关文档?因为即使在w3学校中,它们也只描述SOAP方法。在PHP中创建API的其他选项有哪些?
我们的客户端给了我一个REST API,我需要对它进行PHP调用。但事实上,API提供的文档非常有限,所以我真的不知道如何调用该服务。
我试着谷歌它,但唯一出现的是一个已经过期的雅虎!关于如何调用服务的教程。不要提及标题或任何深入的信息。
是否有关于如何调用REST API的适当信息或相关文档?因为即使在w3学校中,它们也只描述SOAP方法。在PHP中创建API的其他选项有哪些?
当前回答
如果你有一个url并且你的php支持它,你可以调用file_get_contents:
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
如果$response是JSON,使用json_decode将其转换为php数组:
$response = json_decode($response);
如果$response是XML,使用simple_xml类:
$response = new SimpleXMLElement($response);
http://sg2.php.net/manual/en/simplexml.examples-basic.php
其他回答
您可以使用file_get_contents来发出任何http POST/PUT/DELETE/OPTIONS/HEAD方法,除了函数名所示的GET方法之外。
如何在PHP中使用file_get_contents发布数据?
你可以通过php的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;
}
使用狂饮。它是一个“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
您需要知道所调用的REST API是支持GET还是POST,还是同时支持两种方法。下面的代码对我来说是有用的,我正在调用我自己的web服务API,所以我已经知道API需要什么以及它将返回什么。它同时支持GET和POST方法,因此不太敏感的信息会进入URL (GET),而像用户名和密码这样的信息会作为POST变量提交。此外,所有内容都通过HTTPS连接。
在API代码中,我将一个数组编码为json格式,然后简单地使用PHP命令echo $my_json_variable使json字符串对客户端可用。
如您所见,我的API返回json数据,但您需要知道(或查看返回的数据以找出)API响应的格式。
这是我如何从客户端连接到API:
$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()方法,因为这里的一些用户建议,但这并不适合我。我发现旋度法更快更可靠。
如果您正在使用Symfony,有一个很棒的rest客户端包,它甚至包含了所有~100个异常,并抛出它们,而不是返回一些毫无意义的错误代码+消息。
你真的应该检查一下: https://github.com/CircleOfNice/CiRestClientBundle
我喜欢它的界面:
try {
$restClient = new RestClient();
$response = $restClient->get('http://www.someUrl.com');
$statusCode = $response->getStatusCode();
$content = $response->getContent();
} catch(OperationTimedOutException $e) {
// do something
}
适用于所有http方法。