Code Examples

From API Documentation

(Difference between revisions)
Jump to: navigation, search
(Example 2: read the agents/ID resource)
(PHP Class for Making REST Requests)
Line 69: Line 69:
== PHP Class for Making REST Requests ==
== PHP Class for Making REST Requests ==
-
<?php
+
<source lang="php">
-
//*****************************************
+
<?php
-
// The following class handles making the REST request and capturing  
+
//*****************************************
-
// the response from the API. This class is adapted from a script  
+
// The following class handles making the REST request and capturing  
-
// provided in an excellent article on REST API consumption by  
+
// the response from the API. This class is adapted from a script  
-
// Ian Selby, titled "Making RESTful Requests in PHP."
+
// provided in an excellent article on REST API consumption by  
-
// <nowiki>http://www.gen-x-design.com/archives/making-restful-requests-in-php/</nowiki>
+
// Ian Selby, titled "Making RESTful Requests in PHP."
-
//*****************************************
+
// <nowiki>http://www.gen-x-design.com/archives/making-restful-requests-in-php/</nowiki>
-
class API_RestMakeRequest {
+
//*****************************************
-
    protected $url;
+
class API_RestMakeRequest {
-
    protected $verb;
+
    protected $url;
-
    protected $requestBody;
+
    protected $verb;
-
    protected $requestLength;
+
    protected $requestBody;
-
    protected $username;
+
    protected $requestLength;
-
    protected $password;
+
    protected $username;
-
    protected $contentType;
+
    protected $password;
-
    protected $acceptType;
+
    protected $contentType;
-
    protected $responseBody;
+
    protected $acceptType;
-
    protected $responseInfo;
+
    protected $responseBody;
-
    protected $requestInfo;
+
    protected $responseInfo;
-
+
    protected $requestInfo;
-
    public function __construct ($url = null, $verb = 'GET', $requestBody = array()) {
+
 
-
        $this->url                = $url;
+
    public function __construct ($url = null, $verb = 'GET', $requestBody = array()) {
-
        $this->verb                = $verb;
+
        $this->url                = $url;
-
        $this->requestBody        = $requestBody;
+
        $this->verb                = $verb;
-
        $this->requestLength    = 0;
+
        $this->requestBody        = $requestBody;
-
        $this->username            = null;
+
        $this->requestLength    = 0;
-
        $this->password            = null;
+
        $this->username            = null;
-
        $this->contentType        = 'text/plain';
+
        $this->password            = null;
-
        $this->acceptType        = 'text/plain';
+
        $this->contentType        = 'text/plain';
-
        $this->responseBody        = null;
+
        $this->acceptType        = 'text/plain';
-
        $this->responseInfo        = null;
+
        $this->responseBody        = null;
-
        $this->requestInfo        = null;
+
        $this->responseInfo        = null;
-
    }
+
        $this->requestInfo        = null;
-
    public function flush () {
+
    }
-
        $this->requestBody        = null;
+
    public function flush () {
-
        $this->requestLength    = 0;
+
        $this->requestBody        = null;
-
        $this->verb                = 'GET';
+
        $this->requestLength    = 0;
-
        $this->responseBody        = null;
+
        $this->verb                = 'GET';
-
        $this->responseInfo        = null;
+
        $this->responseBody        = null;
-
        $this->requestInfo        = null;
+
        $this->responseInfo        = null;
-
    }
+
        $this->requestInfo        = null;
-
    public function execute () {
+
    }
-
        $ch = curl_init();
+
    public function execute () {
-
        $this->setAuth($ch);
+
        $ch = curl_init();
-
        try {
+
        $this->setAuth($ch);
-
            switch (strtoupper($this->verb)) {
+
        try {
-
                case 'GET':
+
            switch (strtoupper($this->verb)) {
-
                    $this->executeGet($ch);
+
                case 'GET':
-
                    break;
+
                    $this->executeGet($ch);
-
                case 'POST':
+
                    break;
-
                    $this->executePost($ch);
+
                case 'POST':
-
                    break;
+
                    $this->executePost($ch);
-
                case 'PUT':
+
                    break;
-
                    $this->executePut($ch);
+
                case 'PUT':
-
                    break;
+
                    $this->executePut($ch);
-
                case 'DELETE':
+
                    break;
-
                    $this->executeDelete($ch);
+
                case 'DELETE':
-
                    break;
+
                    $this->executeDelete($ch);
-
                default:
+
                    break;
-
                    throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.');
+
                default:
-
            }
+
                    throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.');
-
        }
+
            }
-
        catch (InvalidArgumentException $e) {
+
        }
-
            curl_close($ch);
+
        catch (InvalidArgumentException $e) {
-
            throw $e;
+
            curl_close($ch);
-
        }
+
            throw $e;
-
        catch (Exception $e) {
+
        }
-
            curl_close($ch);
+
        catch (Exception $e) {
-
            throw $e;
+
            curl_close($ch);
-
        }
+
            throw $e;
-
    }
+
        }
-
    public function buildPostBody ($data = null) {
+
    }
-
        $data = ($data !== null) ? $data : $this->requestBody;
+
    public function buildPostBody ($data = null) {
-
        if ($data !== null) {
+
        $data = ($data !== null) ? $data : $this->requestBody;
-
            if (!is_array($data)) {
+
        if ($data !== null) {
-
                throw new InvalidArgumentException('Invalid data input for postBody.  Array expected');
+
            if (!is_array($data)) {
-
            }
+
                throw new InvalidArgumentException('Invalid data input for postBody.  Array expected');
-
            if (strpos($this->contentType, 'json')) {
+
            }
-
                $data = 'data=' . json_encode($data);
+
            if (strpos($this->contentType, 'json')) {
-
            } else if (strpos($this->contentType, 'xml')) {
+
                $data = 'data=' . json_encode($data);
-
                $objXML = new XmlWriter();
+
            } else if (strpos($this->contentType, 'xml')) {
-
                $objXML->openMemory();
+
                $objXML = new XmlWriter();
-
                $objXML->startDocument('1.0', 'UTF-8');
+
                $objXML->openMemory();
-
                API_RestMakeRequest::arrayToXML($objXML, $data, $strItemNode);
+
                $objXML->startDocument('1.0', 'UTF-8');
-
                $data = 'data=' . urlencode($objXML->outputMemory(true));
+
                API_RestMakeRequest::arrayToXML($objXML, $data, $strItemNode);
-
            } else {
+
                $data = 'data=' . urlencode($objXML->outputMemory(true));
-
                $data = http_build_query($data);
+
            } else {
-
            }
+
                $data = http_build_query($data);
-
        }
+
            }
-
        $this->requestBody = $data;
+
        }
-
    }
+
        $this->requestBody = $data;
-
    protected function executeGet ($ch) {
+
    }
-
        if (!is_string($this->requestBody)) {
+
    protected function executeGet ($ch) {
-
            $this->buildPostBody();
+
        if (!is_string($this->requestBody)) {
-
        }
+
            $this->buildPostBody();
-
        if (strlen($this->requestBody) > 0) {
+
        }
-
            $this->url .= '?' . $this->requestBody;
+
        if (strlen($this->requestBody) > 0) {
-
        }
+
            $this->url .= '?' . $this->requestBody;
-
        $this->doExecute($ch);
+
        }
-
    }
+
        $this->doExecute($ch);
-
    protected function executePost ($ch) {
+
    }
-
        if (!is_string($this->requestBody)) {
+
    protected function executePost ($ch) {
-
            $this->buildPostBody();
+
        if (!is_string($this->requestBody)) {
-
        }
+
            $this->buildPostBody();
-
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);
+
        }
-
        curl_setopt($ch, CURLOPT_POST, 1);
+
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);
-
        $this->doExecute($ch);
+
        curl_setopt($ch, CURLOPT_POST, 1);
-
    }
+
        $this->doExecute($ch);
-
    protected function executePut ($ch) {
+
    }
-
        if (!is_string($this->requestBody)) {
+
    protected function executePut ($ch) {
-
            $this->buildPostBody();
+
        if (!is_string($this->requestBody)) {
-
        }
+
            $this->buildPostBody();
-
        $this->requestLength = strlen($this->requestBody);
+
        }
-
        $fh = fopen('php://memory', 'rw');
+
        $this->requestLength = strlen($this->requestBody);
-
        fwrite($fh, $this->requestBody);
+
        $fh = fopen('php://memory', 'rw');
-
        rewind($fh);
+
        fwrite($fh, $this->requestBody);
-
        curl_setopt($ch, CURLOPT_INFILE, $fh);
+
        rewind($fh);
-
        curl_setopt($ch, CURLOPT_INFILESIZE, $this->requestLength);
+
        curl_setopt($ch, CURLOPT_INFILE, $fh);
-
        curl_setopt($ch, CURLOPT_PUT, true);
+
        curl_setopt($ch, CURLOPT_INFILESIZE, $this->requestLength);
-
        $this->doExecute($ch);
+
        curl_setopt($ch, CURLOPT_PUT, true);
-
        fclose($fh);
+
        $this->doExecute($ch);
-
    }
+
        fclose($fh);
-
    protected function executeDelete ($ch) {
+
    }
-
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
+
    protected function executeDelete ($ch) {
-
        $this->doExecute($ch);
+
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
-
    }
+
        $this->doExecute($ch);
-
    protected function doExecute (&$curlHandle) {
+
    }
-
        $this->setCurlOpts($curlHandle);
+
    protected function doExecute (&$curlHandle) {
-
        $this->responseBody = curl_exec($curlHandle);
+
        $this->setCurlOpts($curlHandle);
-
        $this->responseInfo    = curl_getinfo($curlHandle);
+
        $this->responseBody = curl_exec($curlHandle);
-
        $this->requestInfo = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT);
+
        $this->responseInfo    = curl_getinfo($curlHandle);
-
        curl_close($curlHandle);
+
        $this->requestInfo = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT);
-
    }
+
        curl_close($curlHandle);
-
    protected function setCurlOpts (&$curlHandle) {
+
    }
-
        curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10);
+
    protected function setCurlOpts (&$curlHandle) {
-
        curl_setopt($curlHandle, CURLOPT_URL, $this->url);
+
        curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10);
-
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
+
        curl_setopt($curlHandle, CURLOPT_URL, $this->url);
-
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array ('Accept: ' . $this->acceptType, 'Content-type: ' . $this->contentType));
+
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
-
        curl_setopt($curlHandle, CURLINFO_HEADER_OUT, 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) {
+
    protected function setAuth (&$curlHandle) {
-
            curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
+
        if ($this->username !== null && $this->password !== null) {
-
            curl_setopt($curlHandle, CURLOPT_USERPWD, $this->username . ':' . $this->password);
+
            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){
+
    protected function arrayToXML(XMLWriter $objXML, $arrData){
-
            if(is_array($value)){
+
        foreach($arrData as $key => $value){
-
                $this->arrayToXML($objXML, $value);
+
            if(is_array($value)){
-
                continue;
+
                $this->arrayToXML($objXML, $value);
-
            }
+
                continue;
-
            $objXML->writeElement($key, $value);
+
            }
-
        }
+
            $objXML->writeElement($key, $value);
-
    }
+
        }
-
    public function getContentType () {
+
    }
-
        return $this->contentType;
+
    public function getContentType () {
-
    }
+
        return $this->contentType;
-
    public function setContentType ($contentType) {
+
    }
-
        $this->contentType = $contentType;
+
    public function setContentType ($contentType) {
-
    }
+
        $this->contentType = $contentType;
-
    public function getAcceptType () {
+
    }
-
        return $this->acceptType;
+
    public function getAcceptType () {
-
    }
+
        return $this->acceptType;
-
    public function setAcceptType ($acceptType) {
+
    }
-
        $this->acceptType = $acceptType;
+
    public function setAcceptType ($acceptType) {
-
    }
+
        $this->acceptType = $acceptType;
-
    public function getPassword () {
+
    }
-
        return $this->password;
+
    public function getPassword () {
-
    }
+
        return $this->password;
-
    public function setPassword ($password) {
+
    }
-
        $this->password = $password;
+
    public function setPassword ($password) {
-
    }
+
        $this->password = $password;
-
    public function getResponseBody () {
+
    }
-
        return $this->responseBody;
+
    public function getResponseBody () {
-
    }
+
        return $this->responseBody;
-
    public function getResponseInfo () {
+
    }
-
        return $this->responseInfo;
+
    public function getResponseInfo () {
-
    }
+
        return $this->responseInfo;
-
    public function getUrl () {
+
    }
-
        return $this->url;
+
    public function getUrl () {
-
    }
+
        return $this->url;
-
    public function setUrl ($url) {
+
    }
-
        $this->url = $url;
+
    public function setUrl ($url) {
-
    }
+
        $this->url = $url;
-
    public function getUsername () {
+
    }
-
        return $this->username;
+
    public function getUsername () {
-
    }
+
        return $this->username;
-
    public function setUsername ($username) {
+
    }
-
        $this->username = $username;
+
    public function setUsername ($username) {
-
    }
+
        $this->username = $username;
-
    public function getVerb () {
+
    }
-
        return $this->verb;
+
    public function getVerb () {
-
    }
+
        return $this->verb;
-
    public function setVerb ($verb) {
+
    }
-
        $this->verb = $verb;
+
    public function setVerb ($verb) {
-
    }
+
        $this->verb = $verb;
-
    public function getRequestInfo() {
+
    }
-
        return $this->requestInfo;
+
    public function getRequestInfo() {
-
    }
+
        return $this->requestInfo;
-
}
+
    }
-
?>
+
}
 +
?>
 +
</source>

Revision as of 14:39, 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
// 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 = '<nowiki>http://api.rezora.com/v1/</nowiki>';
 
// 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 = '<nowiki>http://api.rezora.com/v1/</nowiki>';
 
// 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 = '<nowiki>agents/1234.xml</nowiki>';
 
// 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."
// <nowiki>http://www.gen-x-design.com/archives/making-restful-requests-in-php/</nowiki>
//*****************************************
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