在PHP中调用REST API

我们的客户已经给了我一个REST API,我需要做一个PHP调用。 但是事实上API提供的文档是非常有限的,所以我真的不知道如何调用这个服务。

我试图Google,但唯一出现的是一个已经过期的雅虎! 教程如何调用服务。 不提及标题或任何深入的信息。

有没有关于如何调用REST API的一些体面的信息,或者有关它的一些文档? 因为即使在W3school,他们也只是描述SOAP方法。 在PHP中制作其他API有什么不同的select?

您可以使用PHP的cURL Extension来访问任何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; } 

如果你有一个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

使用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 

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包括…

  • 可读的HTTP方法支持(GET,PUT,POST,DELETE,HEAD和OPTIONS)
  • 自定义标题
  • 自动“智能”分析
  • 自动有效负载序列化
  • 基本身份validation
  • 客户端证书validation
  • 请求“模板”

防爆。

发送GET请求。 获取自动parsing的JSON响应。

库在响应中注意到JSON Content-Type,并自动将响应parsing为本地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"; 

您将需要知道您所调用的REST API是否支持GET或POST,或两种方法。 下面的代码是对我有用的东西,我打电话给我自己的Web服务API,所以我已经知道什么是API和它将返回。 它同时支持GET和POST方法,因此不太敏感的信息进入URL(GET),并且像username和password这样的信息被作为POSTvariables提交。 另外,一切都通过HTTPS连接。

在API代码中,我编码了一个我想要返回到json格式的数组,然后使用PHP命令echo $ my_json_variable将该jsonstring作为客户端。

正如你所看到的,我的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()方法作为这里build议的一些用户,但是这不适合我。 我发现curl方法更快,更可靠。

实际上有很多客户。 其中之一是害虫 – 检查了这一点。 请记住,这些REST调用是简单的http请求,具有各种方法:GET,POST,PUT和DELETE。

如果你正在使用Symfony,那么还有一个很好的rest客户端软件包,它甚至包含了所有的〜100个exception,并抛出它们而不是返回一些没有意义的错误代码+消息。

你应该真的检查它: 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方法。

除了函数名称所暗示的GET方法之外,您可以使用file_get_contents来发出任何http POST / PUT / DELETE / OPTIONS / HEAD方法。

如何使用file_get_contents在PHP中发布数据?

如果你打开使用第三方工具,你可以看看这个: https : //github.com/CircleOfNice/DoctrineRestDriver

这是使用API​​的全新方式。

首先你定义一个实体来定义input和输出数据的结构,并用数据源对它进行注释:

 /* * @Entity * @DataSource\Select("http://www.myApi.com/products/{id}") * @DataSource\Insert("http://www.myApi.com/products") * @DataSource\Select("http://www.myApi.com/products/update/{id}") * @DataSource\Fetch("http://www.myApi.com/products") * @DataSource\Delete("http://www.myApi.com/products/delete/{id}") */ class Product { private $name; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } } 

现在与REST API进行通信非常简单:

 $product = new Product(); $product->setName('test'); // sends an API request POST http://www.myApi.com/products ... $em->persist($product); $em->flush(); $product->setName('newName'); // sends an API request UPDATE http://www.myApi.com/products/update/1 ... $em->flush();