Blog : Call a REST API in PHP

Call a REST API in PHP


Our client had given me a REST API to which I need to make a PHP call to. 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 on W3schools, they only describes the SOAP method.

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;

}

f 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 =newSimpleXMLElement($response);

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

There are plenty of clients actually. One of them is https://github.com/educoder/pest - check this out. And keep in mind that these REST calls are simple http request with various methods: GET, POST, PUT and DELETE.

Use Guzzle. It's a "PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services". Working with Guzzle is much easier than working with cURL.

Here's an example from the Web site:

$client =newGuzzleHttp\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 is the simplest way to go. Here is a simple call

$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);

You will need to know if the REST API you are calling supports GET or POST, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET and POST methods, so the less sensitive info goes into the URL (GET), and the info like username and password is submitted as POST variables. Also, everything goes over the HTTPS connection.

Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable to make that json string availabe to the client.

So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.

This is how I connect to the API from the client side:

$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;

}