Difference between revisions of "PHP Examples (Rest API)"

From Rackspace Email & Apps API
Jump to: navigation, search
(Sync to latest.)
 
(new php example)
Line 1: Line 1:
 
=== PHP ===
 
=== PHP ===
  
 +
An API library for performing basic operations. This requires the curl and pecl_http PHP extensions:
 
<pre>
 
<pre>
 
<?php
 
<?php
class WebMethods
+
/**
 +
* Needs PHP's curl and pecl_http extensions.
 +
*
 +
* All results are returned as an HttpMessage object.
 +
*/
 +
class ApiServer
 
{
 
{
 +
    const USER_KEY = 'xxxxxxxxxxxxxxxxxxxx';
 +
    const SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
 +
    const USER_AGENT = 'PHP Demo Client';
 +
 
     const VERSION = 'v0';
 
     const VERSION = 'v0';
 
     const SERVER_HOST = 'api.emailsrvr.com';
 
     const SERVER_HOST = 'api.emailsrvr.com';
Line 10: Line 20:
 
     public function get($url_string, $format)
 
     public function get($url_string, $format)
 
     {
 
     {
        $url = $this->getUrl($url_string);
+
         $headers = array("Accept: $format");
         $headers = array();
 
        $this->signRequest($headers);
 
        $this->assignFormat($headers, $format);
 
        $session = curl_init($url);
 
        curl_setopt($session, CURLOPT_HEADER, true);
 
        curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
 
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
 
  
         $response = curl_exec($session);
+
         $curl_session = self::construct_session($url_string, $headers);
        curl_close($session);
 
  
         echo $response;
+
         $http_message = self::send_request($curl_session);
 +
        return $http_message;
 
     }
 
     }
  
     public function post($url_string, $fields, $format)
+
     public function post($url_string, $fields)
 
     {
 
     {
         $url = $this->getUrl($url_string);
+
         $curl_session = self::construct_session($url_string, array());
        $headers = array();
+
 
         $this->signRequest($headers);
+
         curl_setopt($curl_session, CURLOPT_POST, true);
         $this->assignFormat($headers, $format);
+
         curl_setopt($curl_session, CURLOPT_POSTFIELDS, $fields);
        $session = curl_init($url);
 
  
         curl_setopt($session, CURLOPT_HEADER, true);
+
         $http_message = self::send_request($curl_session);
        curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
+
         return $http_message;
        curl_setopt($session, CURLOPT_POST, true);
+
    }
         curl_setopt($session, CURLOPT_POSTFIELDS, $fields);
 
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
 
  
        $response = curl_exec($session);
+
    public function delete($url_string)
         curl_close($session);
+
    {
 +
         $curl_session = self::construct_session($url_string, array());
  
         echo $response;
+
         curl_setopt($curl_session, CURLOPT_CUSTOMREQUEST, 'DELETE');
 +
 
 +
        $http_message = self::send_request($curl_session);
 +
        return $http_message;
 
     }
 
     }
  
     public function put($url_string, $fields, $format)
+
     private function send_request($curl_session)
 
     {
 
     {
         $url = $this->getUrl($url_string);
+
         $response = curl_exec($curl_session);
         $headers = array();
+
         curl_close($curl_session);
        $this->signRequest($headers);
 
        $this->assignFormat($headers, $format);
 
        $session = curl_init($url);
 
  
         curl_setopt($session, CURLOPT_HEADER, true);
+
         return new HttpMessage($response);
        curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
 
        curl_setopt($session, CURLOPT_CUSTOMREQUEST, 'PUT');
 
        curl_setopt($session, CURLOPT_POSTFIELDS, $fields);
 
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
 
 
 
        $response = curl_exec($session);
 
        curl_close($session);
 
 
 
        echo $response;
 
 
     }
 
     }
  
     public function delete($url_string, $format)
+
     private function construct_session($url_string, $existing_headers)
 
     {
 
     {
         $url = $this->getUrl($url_string);
+
         $headers = array_merge(
        $headers = array();
+
                self::authorization_headers(), $existing_headers);
        $this->signRequest($headers);
+
         $url = self::construct_uri($url_string);
         $this->assignFormat($headers, $format);
+
         $curl_session = curl_init($url);
         $session = curl_init($url);
 
  
         curl_setopt($session, CURLOPT_HEADER, true);
+
         curl_setopt($curl_session, CURLOPT_HEADER, true);
         curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
+
         curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($session, CURLOPT_CUSTOMREQUEST, 'DELETE');
+
         curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
 
  
         $response = curl_exec($session);
+
         return $curl_session;
        curl_close($session);
 
 
 
        echo $response;
 
 
     }
 
     }
  
     public function signRequest(&$headers)
+
     private function authorization_headers()
 
     {
 
     {
         $user_agent = 'Api Test';
+
         $time_stamp = date('YmdHis');
        $time_stamp = 'YYYYMMDDHHmmss';
+
 
         $api_key = 'XXXXXXXXXXXXXXXXXXXX';
+
         $data_to_sign = self::USER_KEY . self::USER_AGENT .
        $secret_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
+
            $time_stamp. self::SECRET_KEY;
  
        $data_to_sign = $api_key . $user_agent . $time_stamp . $secret_key;
 
 
         $signature = base64_encode(sha1($data_to_sign, true));
 
         $signature = base64_encode(sha1($data_to_sign, true));
  
         $headers[] = "User-Agent: $user_agent";
+
        $headers = array();
         $headers[] = "X-Api-Signature: $api_key:$time_stamp:$signature";
+
         $headers[] = "User-Agent: " . self::USER_AGENT;
    }
+
         $headers[] = 'X-Api-Signature: ' .
 
+
            self::USER_KEY . ":$time_stamp:$signature";
    public function assignFormat(&$headers, $format)
+
         return $headers;
    {
 
         $headers[] = "Accept: $format";
 
 
     }
 
     }
  
     public function getUrl($url_string)
+
     private function construct_uri($url_string)
 
     {
 
     {
 
         $url = 'http://' . self::SERVER_HOST . '/' . self::VERSION . $url_string;
 
         $url = 'http://' . self::SERVER_HOST . '/' . self::VERSION . $url_string;
Line 109: Line 93:
 
     }
 
     }
 
}
 
}
 +
 +
</pre>
 +
 +
 +
A simple GET:
 +
<pre>
 +
<?php
 +
header('Content-Type:  text/plain');
 +
require_once 'ApiServer.php';
 +
 +
$client = new  ApiServer();
 +
 +
$response = $client->get(
 +
    '/customers/me/domains',
 +
    'text/xml');
 +
 +
echo  $response->getResponseCode() . "\r\n" .
 +
      $response->getHeader("x-error-message") . "\r\n" .
 +
      $response->getBody();
 
?>
 
?>
 
</pre>
 
</pre>
  
 +
 +
A simple POST:
 
<pre>
 
<pre>
 
<?php
 
<?php
require_once 'WebMethods.php';
+
header('Content-Type:  text/plain');
 +
require_once 'ApiServer.php';
  
$client = new WebMethods();
+
$client = new ApiServer();
  
$url = '/customers';
+
$fields  = Array(
$form = 'name=new customer&referenceNumber=1000';
+
    'serviceType' => 'exchange',
$format = 'text/xml';
+
    'exchangeMaxNumMailboxes' => '4');
  
$client->post($url, $form, $format);
+
$response = $client->post(
 +
    '/customers/me/domains/newdomain.com',
 +
    $fields);
 +
 
 +
echo  $response->getResponseCode() . "\r\n" .
 +
      $response->getHeader("x-error-message") . "\r\n" .
 +
      $response->getBody();
 
?>
 
?>
 +
</pre>
 +
 +
A get with paging:
 +
<pre>
 +
<?php
 +
header('Content-Type: text/plain');
 +
require_once 'ApiServer.php';
 +
 +
$client = new ApiServer();
 +
$format = 'application/json';
 +
$domain = 'apiPagingTest.com';
 +
 +
// Get mailboxes. page size defaults to 50.
 +
$url = '/customers/me/domains/' . $domain . '/ex/mailboxes';
 +
$response = $client->get($url, $format);
 +
 +
$body = $response->getBody();
 +
$result = json_decode($response->getBody());
 +
echo $body . "\n";
 +
 +
// check results
 +
$totalSize = $result->{"total"};
 +
$resultSize = $result->{"size"};
 +
 +
// If there are more results, read the rest.
 +
if($totalSize > $resultSize)
 +
{
 +
    // start at last read index and set page size
 +
    $offset = $resultSize;
 +
    $pageSize = 50;
 +
 +
    // read up to the next 50
 +
    $url = '/customers/me/domains/' . $domain . '/ex/mailboxes?size='
 +
                            . $pageSize . '&offset=' . $offset;
 +
    $response = $client->get($url, $format);
 +
    echo $response->getBody(). "\n";
 +
}
 +
 +
?>
 +
 
</pre>
 
</pre>

Revision as of 12:29, 19 May 2010

PHP

An API library for performing basic operations. This requires the curl and pecl_http PHP extensions:

<?php
/**
 * Needs PHP's curl and pecl_http extensions.
 *
 * All results are returned as an HttpMessage object.
 */
class ApiServer
{
    const USER_KEY = 'xxxxxxxxxxxxxxxxxxxx';
    const SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    const USER_AGENT = 'PHP Demo Client';

    const VERSION = 'v0';
    const SERVER_HOST = 'api.emailsrvr.com';

    public function get($url_string, $format)
    {
        $headers = array("Accept: $format");

        $curl_session = self::construct_session($url_string, $headers);

        $http_message = self::send_request($curl_session);
        return $http_message;
    }

    public function post($url_string, $fields)
    {
        $curl_session = self::construct_session($url_string, array());

        curl_setopt($curl_session, CURLOPT_POST, true);
        curl_setopt($curl_session, CURLOPT_POSTFIELDS, $fields);

        $http_message = self::send_request($curl_session);
        return $http_message;
     }

    public function delete($url_string)
    {
        $curl_session = self::construct_session($url_string, array());

        curl_setopt($curl_session, CURLOPT_CUSTOMREQUEST, 'DELETE');

        $http_message = self::send_request($curl_session);
        return $http_message;
    }

    private function send_request($curl_session)
    {
        $response = curl_exec($curl_session);
        curl_close($curl_session);

        return new HttpMessage($response);
    }

    private function construct_session($url_string, $existing_headers)
    {
        $headers = array_merge(
                self::authorization_headers(), $existing_headers);
        $url = self::construct_uri($url_string);
        $curl_session = curl_init($url);

        curl_setopt($curl_session, CURLOPT_HEADER, true);
        curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);

        return $curl_session;
    }

    private function authorization_headers()
    {
        $time_stamp = date('YmdHis');

        $data_to_sign = self::USER_KEY . self::USER_AGENT .
            $time_stamp. self::SECRET_KEY;

        $signature = base64_encode(sha1($data_to_sign, true));

        $headers = array();
        $headers[] = "User-Agent: " . self::USER_AGENT;
        $headers[] = 'X-Api-Signature: ' .
            self::USER_KEY . ":$time_stamp:$signature";
        return $headers;
    }

    private function construct_uri($url_string)
    {
        $url = 'http://' . self::SERVER_HOST . '/' . self::VERSION . $url_string;
        return $url;
    }
}


A simple GET:

<?php
header('Content-Type:  text/plain');
require_once 'ApiServer.php';

$client = new  ApiServer();

$response = $client->get(
    '/customers/me/domains',
    'text/xml');

echo  $response->getResponseCode() . "\r\n" .
      $response->getHeader("x-error-message") . "\r\n" .
      $response->getBody();
?>


A simple POST:

<?php
header('Content-Type:  text/plain');
require_once 'ApiServer.php';

$client = new  ApiServer();

$fields  = Array(
    'serviceType' => 'exchange',
    'exchangeMaxNumMailboxes' => '4');

$response = $client->post(
    '/customers/me/domains/newdomain.com',
    $fields);

echo  $response->getResponseCode() . "\r\n" .
      $response->getHeader("x-error-message") . "\r\n" .
      $response->getBody();
?>

A get with paging:

<?php
header('Content-Type: text/plain');
require_once 'ApiServer.php';

$client = new ApiServer();
$format = 'application/json';
$domain = 'apiPagingTest.com';

// Get mailboxes. page size defaults to 50.
$url = '/customers/me/domains/' . $domain . '/ex/mailboxes';
$response = $client->get($url, $format);

$body = $response->getBody();
$result = json_decode($response->getBody());
echo $body . "\n";

// check results
$totalSize = $result->{"total"};
$resultSize = $result->{"size"};

// If there are more results, read the rest.
if($totalSize > $resultSize)
{
    // start at last read index and set page size
    $offset = $resultSize;
    $pageSize = 50;

    // read up to the next 50
    $url = '/customers/me/domains/' . $domain . '/ex/mailboxes?size='
                            . $pageSize . '&offset=' . $offset;
    $response = $client->get($url, $format);
    echo $response->getBody(). "\n";
}

?>