Code Examples

From API Documentation

(Difference between revisions)
Jump to: navigation, search
(Created page with 'Below are examples of how to access the API using PHP. These examples use the cURL library for handling the HTTP request. The examples us a PHP class for making the REST requests…')
Line 1: Line 1:
Below are examples of how to access the API using PHP. These examples use the cURL library for handling the HTTP request. The examples us a PHP class for making the REST requests. This class is included after the examples.
Below are examples of how to access the API using PHP. These examples use the cURL library for handling the HTTP request. The examples us a PHP class for making the REST requests. This class is included after the examples.
-
'''''Example 1: read the agents collection resource'''''
+
== Example 1: read the agents collection resource ==
-
+
  <?php
  <?php
  // Include the RestMakeRequest class file
  // Include the RestMakeRequest class file
Line 11: Line 10:
  $strUsername = 'YOUR_USERNAME';
  $strUsername = 'YOUR_USERNAME';
  $strPassword = 'YOUR_PASSWORD';
  $strPassword = 'YOUR_PASSWORD';
-
  $strBaseURI = 'http://api.rezora.com/v1/';
+
  $strBaseURI = '<nowiki>http://api.rezora.com/v1/</nowiki>';
-
 
+
  // Set some configuration variables specific to the task at hand.
  // Set some configuration variables specific to the task at hand.
  // In this example, we'll be reading data from the agents collection
  // In this example, we'll be reading data from the agents collection
Line 32: Line 31:
  ?>
  ?>
-
'''''Example 2: read an individual agent resource'''''
+
== Example 2: read an individual agent resource ==
-
+
  <?php
  <?php
  // Include the RestMakeRequest class file
  // Include the RestMakeRequest class file
Line 42: Line 40:
  $strUsername = 'YOUR_USERNAME';
  $strUsername = 'YOUR_USERNAME';
  $strPassword = 'YOUR_PASSWORD';
  $strPassword = 'YOUR_PASSWORD';
-
  $strBaseURI = 'http://api.rezora.com/v1/';
+
  $strBaseURI = '<nowiki>http://api.rezora.com/v1/</nowiki>';
   
   
  // Set some configuration variables specific to the task at hand.
  // Set some configuration variables specific to the task at hand.
  // In this example, we'll be reading data from the resource for
  // In this example, we'll be reading data from the resource for
  // an agent with the ID 1234. We'll retrieve the data in XML format.
  // an agent with the ID 1234. We'll retrieve the data in XML format.
-
  $strResourcePath = 'agents/1234.xml';
+
  $strResourcePath = '<nowiki>agents/1234.xml</nowiki>';
   
   
  // Create an instance of the RestMakeRequest.
  // Create an instance of the RestMakeRequest.
Line 63: Line 61:
  ?>
  ?>
-
'''''PHP Class for Making REST Requests'''''
+
== PHP Class for Making REST Requests ==
-
+
  <?php
  <?php
  //*****************************************
  //*****************************************
Line 71: Line 68:
  // provided in an excellent article on REST API consumption by  
  // provided in an excellent article on REST API consumption by  
  // Ian Selby, titled "Making RESTful Requests in PHP."
  // Ian Selby, titled "Making RESTful Requests in PHP."
-
  // http://www.gen-x-design.com/archives/making-restful-requests-in-php/
+
  // <nowiki>http://www.gen-x-design.com/archives/making-restful-requests-in-php/</nowiki>
  //*****************************************
  //*****************************************
  class API_RestMakeRequest {
  class API_RestMakeRequest {

Revision as of 07:32, 10 July 2010

Below are examples of how to access the API using PHP. These examples use the cURL library for handling the HTTP request. The examples us a PHP class for making the REST requests. This class is included after the examples.

Example 1: read the agents collection resource

<?php
// Include the RestMakeRequest class file
include_once 'RestMakeRequest.php';

// Set some universal configuration variables. These will be
// the same for all your API requests for a particular account.
$strUsername = 'YOUR_USERNAME';
$strPassword = 'YOUR_PASSWORD';
$strBaseURI = 'http://api.rezora.com/v1/';

// Set some configuration variables specific to the task at hand.
// In this example, we'll be reading data from the agents collection
// resource. We'll retrieve the data in text format.
$strResourcePath = 'agents';

// Create an instance of the RestMakeRequest.
$objRequest = new RestMakeRequest($strBaseURI . $strResourcePath);

// Set the necessary parameters.
$objRequest->setUsername($strUsername);
$objRequest->setPassword($strPassword);

// Make the request and capture the response.
$objRequest->execute();

// Output the response data.
echo $objRequest->getResponseBody();
?>

Example 2: read an individual agent resource

<?php
// Include the RestMakeRequest class file
include_once 'RestMakeRequest.php';

// Set some universal configuration variables. These will be
// the same for all your API requests for a particular account.
$strUsername = 'YOUR_USERNAME';
$strPassword = 'YOUR_PASSWORD';
$strBaseURI = 'http://api.rezora.com/v1/';

// Set some configuration variables specific to the task at hand.
// In this example, we'll be reading data from the resource for
// an agent with the ID 1234. We'll retrieve the data in XML format.
$strResourcePath = 'agents/1234.xml';

// Create an instance of the RestMakeRequest.
$objRequest = new RestMakeRequest($strBaseURI . $strResourcePath);

// Set the necessary parameters.
$objRequest->setUsername($strUsername);
$objRequest->setPassword($strPassword);

// Make the request and capture the response.
$objRequest->execute();

// Output the response data.
echo $objRequest->getResponseBody();
?>

PHP Class for Making REST Requests

<?php
//*****************************************
// The following class handles making the REST request and capturing 
// the response from the API. This class is adapted from a script 
// provided in an excellent article on REST API consumption by 
// Ian Selby, titled "Making RESTful Requests in PHP."
// http://www.gen-x-design.com/archives/making-restful-requests-in-php/
//*****************************************
class API_RestMakeRequest {
    protected $url;
    protected $verb;
    protected $requestBody;
    protected $requestLength;
    protected $username;
    protected $password;
    protected $contentType;
    protected $acceptType;
    protected $responseBody;
    protected $responseInfo;
    protected $requestInfo;

    public function __construct ($url = null, $verb = 'GET', $requestBody = array()) {
        $this->url                = $url;
        $this->verb                = $verb;
        $this->requestBody        = $requestBody;
        $this->requestLength    = 0;
        $this->username            = null;
        $this->password            = null;
        $this->contentType        = 'text/plain';
        $this->acceptType        = 'text/plain';
        $this->responseBody        = null;
        $this->responseInfo        = null;
        $this->requestInfo        = null;
    }
    public function flush () {
        $this->requestBody        = null;
        $this->requestLength    = 0;
        $this->verb                = 'GET';
        $this->responseBody        = null;
        $this->responseInfo        = null;
        $this->requestInfo        = null;
    }
    public function execute () {
        $ch = curl_init();
        $this->setAuth($ch);
        try {
            switch (strtoupper($this->verb)) {
                case 'GET':
                    $this->executeGet($ch);
                    break;
                case 'POST':
                    $this->executePost($ch);
                    break;
                case 'PUT':
                    $this->executePut($ch);
                    break;
                case 'DELETE':
                    $this->executeDelete($ch);
                    break;
                default:
                    throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.');
            }
        }
        catch (InvalidArgumentException $e) {
            curl_close($ch);
            throw $e;
        }
        catch (Exception $e) {
            curl_close($ch);
            throw $e;
        }
    }
    public function buildPostBody ($data = null) {
        $data = ($data !== null) ? $data : $this->requestBody;
        if ($data !== null) {
            if (!is_array($data)) {
                throw new InvalidArgumentException('Invalid data input for postBody.  Array expected');
            }
            if (strpos($this->contentType, 'json')) {
                $data = 'data=' . json_encode($data);
            } else if (strpos($this->contentType, 'xml')) {
                $objXML = new XmlWriter();
                $objXML->openMemory();
                $objXML->startDocument('1.0', 'UTF-8');
                API_RestMakeRequest::arrayToXML($objXML, $data, $strItemNode);
                $data = 'data=' . urlencode($objXML->outputMemory(true));
            } else {
                $data = http_build_query($data);
            }
        }
        $this->requestBody = $data;
    }
    protected function executeGet ($ch) {
        if (!is_string($this->requestBody)) {
            $this->buildPostBody();
        }
        if (strlen($this->requestBody) > 0) {
            $this->url .= '?' . $this->requestBody;
        }
        $this->doExecute($ch);
    }
    protected function executePost ($ch) {
        if (!is_string($this->requestBody)) {
            $this->buildPostBody();
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);
        curl_setopt($ch, CURLOPT_POST, 1);
        $this->doExecute($ch);
    }
    protected function executePut ($ch) {
        if (!is_string($this->requestBody)) {
            $this->buildPostBody();
        }
        $this->requestLength = strlen($this->requestBody);
        $fh = fopen('php://memory', 'rw');
        fwrite($fh, $this->requestBody);
        rewind($fh);
        curl_setopt($ch, CURLOPT_INFILE, $fh);
        curl_setopt($ch, CURLOPT_INFILESIZE, $this->requestLength);
        curl_setopt($ch, CURLOPT_PUT, true);
        $this->doExecute($ch);
        fclose($fh);
    }
    protected function executeDelete ($ch) {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        $this->doExecute($ch);
    }
    protected function doExecute (&$curlHandle) {
        $this->setCurlOpts($curlHandle);
        $this->responseBody = curl_exec($curlHandle);
        $this->responseInfo    = curl_getinfo($curlHandle);
        $this->requestInfo = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT);
        curl_close($curlHandle);
    }
    protected function setCurlOpts (&$curlHandle) {
        curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10);
        curl_setopt($curlHandle, CURLOPT_URL, $this->url);
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array ('Accept: ' . $this->acceptType, 'Content-type: ' . $this->contentType));
        curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true);
    }
    protected function setAuth (&$curlHandle) {
        if ($this->username !== null && $this->password !== null) {
            curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
            curl_setopt($curlHandle, CURLOPT_USERPWD, $this->username . ':' . $this->password);
        }
    }
    protected function arrayToXML(XMLWriter $objXML, $arrData){
        foreach($arrData as $key => $value){
            if(is_array($value)){
                $this->arrayToXML($objXML, $value);
                continue;
            }
            $objXML->writeElement($key, $value);
        }
    }
    public function getContentType () {
        return $this->contentType;
    }
    public function setContentType ($contentType) {
        $this->contentType = $contentType;
    }
    public function getAcceptType () {
        return $this->acceptType;
    }
    public function setAcceptType ($acceptType) {
        $this->acceptType = $acceptType;
    }
    public function getPassword () {
        return $this->password;
    }
    public function setPassword ($password) {
        $this->password = $password;
    }
    public function getResponseBody () {
        return $this->responseBody;
    }
    public function getResponseInfo () {
        return $this->responseInfo;
    }
    public function getUrl () {
        return $this->url;
    }
    public function setUrl ($url) {
        $this->url = $url;
    }
    public function getUsername () {
        return $this->username;
    }
    public function setUsername ($username) {
        $this->username = $username;
    }
    public function getVerb () {
        return $this->verb;
    }
    public function setVerb ($verb) {
        $this->verb = $verb;
    }
    public function getRequestInfo() {
        return $this->requestInfo;
    }
}
?>
Personal tools