Code Examples

From API Documentation

(Difference between revisions)
Jump to: navigation, search
Line 1: Line 1:
-
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.
+
Below are examples of how to access the API using PHP. These examples demonstrate a variety of available methods and content formats. While we do not cover every possible use of the API here, these examples meant to be indicative of all API calls.
 +
 
 +
All examples use the cURL library for handling the HTTP request. There are other methods available in PHP (and other languages, of course), and any means that allows you to send and receive the properly formatted requests and responses is perfectly acceptable.
== Example 1: read the ''agents'' collection resource ==
== Example 1: read the ''agents'' collection resource ==
Line 73: Line 75:
</source>
</source>
-
== PHP Class for Making REST Requests ==
+
== Example 3: post a new contact to the ''contacts'' collection resource ==
<source lang="php">
<source lang="php">
<?php
<?php
-
//*****************************************
+
// Set some universal configuration variables. These will be
-
// The following class handles making the REST request and capturing
+
// the same for all your API requests for a particular account.
-
// the response from the API. This class is adapted from a script
+
$strUsername = 'hmorgan';
-
// provided in an excellent article on REST API consumption by
+
$strPassword = 'd7720f94da2080e4168ed2664356b8ba1ffbfb17';
-
// Ian Selby, titled "Making RESTful Requests in PHP."
+
$strBaseURI = 'http://api.rezora.com/v1/';
-
// 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()) {
+
// Set some configuration variables specific to the task at hand.
-
        $this->url                = $url;
+
// In this example, we'll be posting data to the contacts collection
-
        $this->verb                = $verb;
+
// resource to create a new contact. We'll post data in JSON format,
-
        $this->requestBody        = $requestBody;
+
// and retrieve data in XML format.
-
        $this->requestLength    = 0;
+
$strResourcePath = 'contacts';
-
        $this->username            = null;
+
$strRequestFormat = 'application/xml';
-
        $this->password            = null;
+
$strResponseFormat = 'application/json';
-
        $this->contentType        = 'text/plain';
+
$strData = '{
-
        $this->acceptType        = 'text/plain';
+
"data":{
-
        $this->responseBody        = null;
+
  "contact_name":"Jane Smith",
-
        $this->responseInfo        = null;
+
  "contact_email":"jane.smith@company.com",
-
        $this->requestInfo        = null;
+
  "contact_type":"Active",
-
    }
+
  "contact_title":"Consultant",
-
    public function flush () {
+
  "contact_company":"Acme Consulting",
-
        $this->requestBody        = null;
+
  "contact_phone_home":"303-555-1234",
-
        $this->requestLength    = 0;
+
  "contact_phone_work":"303-555-1235",
-
        $this->verb                = 'GET';
+
  "contact_phone_mobile":"303-555-1236",
-
        $this->responseBody        = null;
+
  "contact_phone_fax":"303-555-1237",
-
        $this->responseInfo        = null;
+
  "contact_business_street":"123 Church Street",
-
        $this->requestInfo        = null;
+
  "contact_business_street2":"Suite 12",
-
    }
+
  "contact_business_city":"Shady Acres",
-
    public function execute () {
+
  "contact_business_state":"CO",
-
        $ch = curl_init();
+
  "contact_business_zip":"12345",
-
        $this->setAuth($ch);
+
  "contact_home_street":"124 Church Street",
-
        try {
+
  "contact_home_street2":"",
-
            switch (strtoupper($this->verb)) {
+
  "contact_home_city":"Shady Acres",
-
                case 'GET':
+
  "contact_home_state":"CO",
-
                    $this->executeGet($ch);
+
  "contact_home_zip":"12345"
-
                    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;
+
-
    }
+
}
}
 +
';
 +
 +
// Open a cURL resource
 +
$ch = curl_init();
 +
 +
// Set the necessary parameters
 +
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
 +
curl_setopt($ch, CURLOPT_USERPWD, $strUsername . ':' . $strPassword);
 +
curl_setopt($ch, CURLOPT_URL, $strBaseURI . $strResourcePath);
 +
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: ' . $strResponseFormat, 'Content-type: ' . $strRequestFormat));
 +
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 +
curl_setopt($ch, CURLOPT_POST, true);
 +
curl_setopt($ch, CURLOPT_POSTFIELDS, $strData);
 +
 +
// Make the request and output the response.
 +
echo curl_exec($ch);
 +
 +
// Close the cURL resource
 +
curl_close($ch);
?>
?>
</source>
</source>

Revision as of 05:06, 18 July 2010

Below are examples of how to access the API using PHP. These examples demonstrate a variety of available methods and content formats. While we do not cover every possible use of the API here, these examples meant to be indicative of all API calls.

All examples use the cURL library for handling the HTTP request. There are other methods available in PHP (and other languages, of course), and any means that allows you to send and receive the properly formatted requests and responses is perfectly acceptable.

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 = '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';
$strRequestFormat = 'text/plain';
$strResponseFormat = 'text/plain';
 
// Open a cURL resource
$ch = curl_init();
 
// Set the necessary parameters
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, $strUsername . ':' . $strPassword);
curl_setopt($ch, CURLOPT_URL, $strBaseURI . $strResourcePath);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: ' . $strResponseFormat, 'Content-type: ' . $strRequestFormat));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 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
// 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.
// Notice that the presence of the .xml extension will override the
// Accept header value ($strRresponseFormat). Alternatively, you
// could leave off the extension and set the Accept header value
// ($strRresponseFormat) to application/xml.
$strResourcePath = 'agents/1234.xml';
$strRequestFormat = 'text/plain';
$strResponseFormat = 'text/plain';
 
// Open a cURL resource
$ch = curl_init();
 
// Set the necessary parameters
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, $strUsername . ':' . $strPassword);
curl_setopt($ch, CURLOPT_URL, $strBaseURI . $strResourcePath);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: ' . $strResponseFormat, 'Content-type: ' . $strRequestFormat));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
// Make the request and output the response.
echo curl_exec($ch);
 
// Close the cURL resource
curl_close($ch);
?>

Example 3: post a new contact to the contacts collection resource

<?php
// Set some universal configuration variables. These will be
// the same for all your API requests for a particular account.
$strUsername = 'hmorgan';
$strPassword = 'd7720f94da2080e4168ed2664356b8ba1ffbfb17';
$strBaseURI = 'http://api.rezora.com/v1/';
 
// Set some configuration variables specific to the task at hand.
// In this example, we'll be posting data to the contacts collection
// resource to create a new contact. We'll post data in JSON format,
// and retrieve data in XML format.
$strResourcePath = 'contacts';
$strRequestFormat = 'application/xml';
$strResponseFormat = 'application/json';
$strData = '{
 "data":{
  "contact_name":"Jane Smith",
  "contact_email":"jane.smith@company.com",
  "contact_type":"Active",
  "contact_title":"Consultant",
  "contact_company":"Acme Consulting",
  "contact_phone_home":"303-555-1234",
  "contact_phone_work":"303-555-1235",
  "contact_phone_mobile":"303-555-1236",
  "contact_phone_fax":"303-555-1237",
  "contact_business_street":"123 Church Street",
  "contact_business_street2":"Suite 12",
  "contact_business_city":"Shady Acres",
  "contact_business_state":"CO",
  "contact_business_zip":"12345",
  "contact_home_street":"124 Church Street",
  "contact_home_street2":"",
  "contact_home_city":"Shady Acres",
  "contact_home_state":"CO",
  "contact_home_zip":"12345"
 }
}
';
 
// Open a cURL resource
$ch = curl_init();
 
// Set the necessary parameters
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, $strUsername . ':' . $strPassword);
curl_setopt($ch, CURLOPT_URL, $strBaseURI . $strResourcePath);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: ' . $strResponseFormat, 'Content-type: ' . $strRequestFormat));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $strData);
 
// Make the request and output the response.
echo curl_exec($ch);
 
// Close the cURL resource
curl_close($ch);
?>
Personal tools