Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a REST API in PHP

Our client had given me a REST API to which I need to make a PHP call. But as a matter of fact, the documentation given with the API is very limited, so I don't really know how to call the service.

I've tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in-depth information.

Is there any decent information around how to call a REST API or some documentation about it? Because even in W3schools, they only describe the SOAP method. What are different options for making the rest of API in PHP?

like image 566
Michiel Avatar asked Mar 21 '12 10:03

Michiel


People also ask

Does PHP support REST API?

PHP is specially suited to make developing REST services easy. Remember REST is the application of the same http patterns that already exists.


2 Answers

You can access any REST API with PHPs cURL Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!

Example:

// 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; } 
like image 105
Christoph Winkler Avatar answered Sep 21 '22 20:09

Christoph Winkler


If you have a url and your php supports it, you could just call file_get_contents:

$response = file_get_contents('http://example.com/path/to/api/call?param1=5'); 

if $response is JSON, use json_decode to turn it into php array:

$response = json_decode($response); 

if $response is XML, use simple_xml class:

$response = new SimpleXMLElement($response); 

http://sg2.php.net/manual/en/simplexml.examples-basic.php

like image 33
Andreas Wong Avatar answered Sep 17 '22 20:09

Andreas Wong