PHP: REST calls

Possible solutions

Request

  • file_get_contents
    • Easy to implement
    • No default support for HTTP POST
    • Parameters containing spaces or other illegal character in an URL must be encoded using urlencode
  • jQuery.ajax ($.get, $.post, $.getJSON)
    • JSONP: no error-handling, no 404 detection, no request restart or abort
  • Curl
    • Supports HTTPS, HTTP POST

Response

  • XML
  • JSON
  • Serialized PHP (serialize and unserialize)
  • (X)HTML

file_get_contents

HTTP GET

$request = 'http://www.domain.com/servicename?name=' . urlencode('Name of param');
file_get_contents($request);

HTTP POST

$params = array(
		'id' => 1234,
		'name' => 'name'
		);
 
// Create a context for the query to perform a POST
$post = http_build_query($params);
$options = array('http' =>
	        array(
		      'method'  => 'POST',
		      'header'  => 'Content-type: application/x-www-form-urlencoded',
		      'content' => $post
		    )
	        );
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

Error handling
The HTTP status code is set in the global array $http_response_header.

file_get_contents(‘http://www.domainn.com‘);
var_dump($http_response_header);
 
array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}
 
list($version, $status_code, $msg) = explode(' ',  $http_response_header[0],  3);
 
switch ( $status_code )  {
       case 200:
       // Success
       break;
       case 503:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 503. That means: Service unavailable. An internal problem prevented us from returning data to you.');
       break;
       case 403:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 403. That means: Forbidden. You do not have permission to access this resource, or are over your rate limit.');
       break;
       case 400:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 400. That means:  Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
       break;
       default:
       die('Your call to Yahoo Web Services returned an unexpected HTTP status of:' . $status_code[0]);
 }

jQuery.ajax (crossdomain)

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: jsonp
});

Leave a Reply