Mic*_*iel 292 php api rest web-services
我们的客户给了我一个REST API,我需要对它进行PHP调用.但事实上,API提供的文档非常有限,所以我真的不知道如何调用该服务.
我试过谷歌它,但唯一出现的是已经过期的雅虎!关于如何调用服务的教程.没有提到标题或任何深度信息.
是否有关于如何调用REST API或有关它的一些文档的正确信息?因为即使在W3schools上,他们也只描述了SOAP方法.在PHP中制作rest API有哪些不同的选择?
Chr*_*ler 405
您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
And*_*ong 170
如果你有一个url并且你的php支持它,你可以调用file_get_contents:
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
Run Code Online (Sandbox Code Playgroud)
如果$ response是JSON,请使用json_decode将其转换为php数组:
$response = json_decode($response);
Run Code Online (Sandbox Code Playgroud)
如果$ response是XML,请使用simple_xml类:
$response = new SimpleXMLElement($response);
Run Code Online (Sandbox Code Playgroud)
http://sg2.php.net/manual/en/simplexml.examples-basic.php
col*_*lan 146
使用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
Run Code Online (Sandbox Code Playgroud)
Bro*_*cha 18
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);
Run Code Online (Sandbox Code Playgroud)
Som*_*luk 11
使用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";
Run Code Online (Sandbox Code Playgroud)
你需要知道,如果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;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我也试图file_get_contents()像这里建议的一些用户那样使用方法,但这对我来说效果不错.我发现curl方法更快更可靠.
除了函数名称所暗示的方法之外,您还可以使用它file_get_contents来发出任何 httpPOST/PUT/DELETE/OPTIONS/HEAD方法GET。
如何使用file_get_contents在PHP中发布数据?
正如@Christoph Winkler 提到的,这是实现它的基类:
curl_helper.php
// 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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你总是可以包含文件并使用它,例如:any.php
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
624201 次 |
| 最近记录: |