Quantcast
Channel: How To – Paul K Leasure
Viewing all articles
Browse latest Browse all 39

Simple REST Client in PHP

$
0
0

A while back I created a Drupal module to act as a customized and extensible REST client. Since then I have used the module as a basis for other customized REST client code. I thought it might be a good idea to keep a copy of the dumbed down very basic code (not the Drupal module) in this post as a reference for myself and others to build off of in the future.

Any improvements or suggestions are welcome. However, please keep in mind that this is intended to be a scaffold on which to build customizations.

<?php

$url = 'https://www.someRestAPI.com';
$method = 'POST';

// Set the headers. In this case its for JSON
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);

$data_array = SomeDataRetrievingClass::GetData($param) ;

// Convert array to JSON
$data = json_encode($data_array);

//  PHP cURL Documentation:  http://php.net/manual/en/book.curl.php
//  See list of cURL options to set:  http://php.net/manual/en/function.curl-setopt.php

$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);

switch($method){

case 'GET':
break;

case 'POST':
curl_setopt($handle, CURLOPT_POST, TRUE);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;

case 'PUT':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;

case 'DELETE':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}

$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);

?>


Viewing all articles
Browse latest Browse all 39

Trending Articles