Code Examples

From API Documentation

(Difference between revisions)
Jump to: navigation, search
(Example 1: read the agents collection resource)
Line 17: Line 17:
  $strResourcePath = 'agents';
  $strResourcePath = 'agents';
   
   
-
  // Create an instance of the RestMakeRequest.
+
  // Open a cURL resource
-
  $objRequest = new RestMakeRequest($strBaseURI . $strResourcePath);
+
  $ch = curl_init();
   
   
-
  // Set the necessary parameters.
+
  // Set the necessary parameters
-
  $objRequest->setUsername($strUsername);
+
  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
-
  $objRequest->setPassword($strPassword);
+
curl_setopt($ch, CURLOPT_USERPWD, 'cbrbden:8d09bd3b77779056b9f02d73f02a00b0fc9bf867');
 +
  curl_setopt($ch, CURLOPT_HEADER, true);
 +
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
 +
curl_setopt($ch, CURLOPT_URL, $strBaseURI . $strResourcePath);
 +
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 +
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: text/plain', 'Content-type: text/plain'));
 +
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
   
   
-
  // Make the request and capture the response.
+
  // Make the request and output the response.
-
  $objRequest->execute();
+
  echo curl_exec($ch);
   
   
-
  // Output the response data.
+
  // Close the cURL resource
-
  echo $objRequest->getResponseBody();
+
  curl_close($ch);
  ?>
  ?>

Revision as of 14:11, 12 July 2010

Below are examples of how to access the API using PHP. All examples use the cURL library for handling the HTTP request. Most examples use 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';

// Open a cURL resource
$ch = curl_init();

// Set the necessary parameters
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, 'cbrbden:8d09bd3b77779056b9f02d73f02a00b0fc9bf867');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_URL, $strBaseURI . $strResourcePath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: text/plain', 'Content-type: text/plain'));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

// Make the request and output the response.
echo curl_exec($ch);

// Close the cURL resource
curl_close($ch);
?>

Example 2: read the agents/ID 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