Difference between revisions of "How To and Samples"

From SRP API Docs

(PHP simple XML list)
(PHP chart)
Line 158: Line 158:
  
 
==== PHP chart ====
 
==== PHP chart ====
 +
Script uses SRP API to fetch UK products, counts asset class popularity and using Google Charts API displays them in a pie.
 +
 +
<pre>
 +
<?php
 +
 +
class ApiClient
 +
{
 +
    /**
 +
    * Domain name
 +
    *
 +
    * @var string
 +
    */
 +
    const DOMAIN = 'http://api.structuredretailproducts.loc';
 +
   
 +
    /**
 +
    * Public API key
 +
    *
 +
    * @var string
 +
    */
 +
    const PUBLIC_API_KEY = '68uxlB048m2lEKwiuiWRAaBzxe3nwdfO';
 +
 +
    /**
 +
    * Private API key
 +
    *
 +
    * @var string
 +
    */
 +
    const PRIVATE_API_KEY = '68uxlB048m2lEKwiuiWRAaBzxe3nwdfO6N5aENMrEnz0hGw0uUw934ogaGC8U9OW';
 +
   
 +
    /**
 +
    * Response
 +
    *
 +
    * @var string
 +
    */
 +
    protected $_strResponse = null;
 +
   
 +
    /**
 +
    * Builds auth header
 +
    *
 +
    * @param string $strMethod
 +
    * @param string $strUri
 +
    * @param int $intContentLength
 +
    * @param string $strContentMD5
 +
    * @return string
 +
    */
 +
    protected function _getAuthHeader( $strMethod, $strUri, $intContentLength, $strContentMD5)
 +
    {
 +
        $intTimestamp = mktime();
 +
       
 +
        $strStringToSign = "$strMethod $strUri $intContentLength $strContentMD5 $intTimestamp";
 +
        $strRawSignature = hash_hmac( 'sha1', $strStringToSign, self::PRIVATE_API_KEY, true);
 +
        $strSignature = base64_encode( $strRawSignature);
 +
 +
        $strAuth = "SRP ". self::PUBLIC_API_KEY. ":$strSignature:$intTimestamp";
 +
       
 +
        return $strAuth;
 +
    }
 +
   
 +
    /**
 +
    * Makes an API call
 +
    *
 +
    * @param string $strMethod
 +
    * @param string $strUri
 +
    * @return int status
 +
    */
 +
    public function call( $strMethod, $strUri)
 +
    {
 +
        $resCurl = curl_init();
 +
       
 +
        // Setting options
 +
        curl_setopt( $resCurl, CURLOPT_URL, self::DOMAIN. $strUri);
 +
        curl_setopt( $resCurl, CURLOPT_RETURNTRANSFER, true);
 +
        curl_setopt( $resCurl, CURLOPT_SSL_VERIFYHOST, false);
 +
        curl_setopt( $resCurl, CURLOPT_SSL_VERIFYPEER, false);
 +
       
 +
        $strContent = null;
 +
 +
        // Setting method dependant options
 +
        switch( $strMethod)
 +
        {
 +
            case 'GET':
 +
                $intContentLength = null;
 +
                $strContentMD5 = null;
 +
            break;
 +
           
 +
            case 'POST':
 +
                curl_setopt( $resCurl, CURLOPT_POST, true);
 +
                curl_setopt( $resCurl, CURLOPT_POSTFIELDS, $strContent);
 +
                $intContentLength = strlen( $strContent);
 +
                $strContentMD5 = md5( $strContent);
 +
            break;
 +
           
 +
            case 'PUT':
 +
                curl_setopt( $resCurl, CURLOPT_CUSTOMREQUEST, 'PUT');
 +
                curl_setopt( $resCurl, CURLOPT_POSTFIELDS, $strContent);
 +
                $intContentLength = strlen( $strContent);
 +
                $strContentMD5 = md5( $strContent);
 +
            break;
 +
           
 +
            case 'DELETE':
 +
                curl_setopt( $resCurl, CURLOPT_CUSTOMREQUEST, 'DELETE');
 +
                $intContentLength = strlen( $strContent);
 +
                $strContentMD5 = md5( $strContent);
 +
            break;
 +
           
 +
            default:
 +
            break;
 +
        }
 +
       
 +
        // building and setting headers
 +
        $arrHeaders = array( 'Authorization: '. $this->_getAuthHeader( $strMethod, $strUri, $intContentLength, $strContentMD5),
 +
                            'Content-Length: '. $intContentLength,
 +
                            'Content-MD5: '. $strContentMD5);
 +
 +
        curl_setopt( $resCurl, CURLOPT_HTTPHEADER, $arrHeaders);
 +
       
 +
        // Making an API call
 +
        $this->_strResponse = curl_exec( $resCurl);
 +
        if ( $this->_strResponse === false)
 +
            throw new Exception( 'Failed to make an SRP API call');
 +
        else
 +
            return curl_getinfo( $resCurl, CURLINFO_HTTP_CODE);
 +
    }
 +
   
 +
    /**
 +
    * Gets an API call response
 +
    *
 +
    * @return string
 +
    */
 +
    public function getResponse()
 +
    {
 +
        return $this->_strResponse;
 +
    }
 +
}
 +
 +
// Retrieving id, name and provider for UK products
 +
$objApi = new ApiClient();
 +
$intStatus = $objApi->call( 'GET', '/v1/products/products?market=MK0012&include=id,asset_class');
 +
 +
if ( $intStatus !== 200)
 +
    throw new Exception( 'Error occured. Status code is '. $intStatus);
 +
 +
// Processing data and counting asset class popularity
 +
$objProducts = new SimpleXMLElement( $objApi->getResponse());
 +
$arrAssetClasses = array();
 +
foreach ( $objProducts->list->product as $objProduct)
 +
    foreach ( $objProduct->asset_classes as $objAssetClass)
 +
    {
 +
        $strCode = (string) $objAssetClass->asset_class->code;
 +
        $strName = (string) $objAssetClass->asset_class->name;
 +
        if ( ! isset( $arrAssetClasses[$strCode]))
 +
            $arrAssetClasses[$strCode] = array( $strName, 1);
 +
        else
 +
            $arrAssetClasses[$strCode][1] = $arrAssetClasses[$strCode][1] + 1;
 +
    }
 +
 +
// preparing data for chart
 +
$arrData = json_encode( array_values( $arrAssetClasses));
 +
 +
// further script uses google charts API to display our data in a pie chart
 +
?>
 +
<html>
 +
  <head>
 +
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
 +
    <script type="text/javascript">
 +
      google.load("visualization", "1", {packages:["corechart"]});
 +
      google.setOnLoadCallback(drawChart);
 +
      function drawChart() {
 +
        var data = new google.visualization.DataTable();
 +
        data.addColumn('string', 'Asset class');
 +
        data.addColumn('number', 'Popularity');
 +
        data.addRows(<?php echo $arrData; ?>);
 +
        var options = { title: 'Popularity of asset classes in UK'};
 +
 +
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
 +
        chart.draw(data, options);
 +
      }
 +
    </script>
 +
  </head>
 +
  <body>
 +
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
 +
  </body>
 +
</html>
 +
</pre>

Revision as of 16:34, 17 April 2012

How To and Samples

Authentication

PHP

To create HMAC-SHA1 signature you can use:

$strPrivateApiKey = 'Jx1qfZA1OLgj5s6A8wzHI7T9aHb2b1zHItPATXPPJNwHBx17HZjKhnoLGJFX7t75';
$strStringToSign = 'GET /v1/products?market=MK0012 257 e4693df9ec5136eec8af95c1dd029a06 1328092781';
$strRawSignature = hash_hmac( 'sha1', $strStringToSign, $strPrivateApiKey, true);
$strSignature = base64_encode( $strRawSignature );

Client

PHP simple XML list

Simple API client using cUrl library.

<?php

class ApiClient
{
    /**
     * Domain name
     * 
     * @var string
     */
    const DOMAIN = 'http://api.structuredretailproducts.loc';
    
    /**
     * Public API key
     * 
     * @var string
     */
    const PUBLIC_API_KEY = '68uxlB048m2lEKwiuiWRAaBzxe3nwdfO';

    /**
     * Private API key
     * 
     * @var string
     */
    const PRIVATE_API_KEY = '68uxlB048m2lEKwiuiWRAaBzxe3nwdfO6N5aENMrEnz0hGw0uUw934ogaGC8U9OW';
    
    /**
     * Response
     * 
     * @var string
     */
    protected $_strResponse = null;
    
    /**
     * Builds auth header
     * 
     * @param string $strMethod
     * @param string $strUri
     * @param int $intContentLength
     * @param string $strContentMD5
     * @return string
     */
    protected function _getAuthHeader( $strMethod, $strUri, $intContentLength, $strContentMD5)
    {
        $intTimestamp = mktime();
        
        $strStringToSign = "$strMethod $strUri $intContentLength $strContentMD5 $intTimestamp";
        $strRawSignature = hash_hmac( 'sha1', $strStringToSign, self::PRIVATE_API_KEY, true);
        $strSignature = base64_encode( $strRawSignature);

        $strAuth = "SRP ". self::PUBLIC_API_KEY. ":$strSignature:$intTimestamp";
        
        return $strAuth;
    }
    
    /**
     * Makes an API call
     * 
     * @param string $strMethod
     * @param string $strUri
     * @return int status
     */
    public function call( $strMethod, $strUri)
    {
        $resCurl = curl_init();
        
        // Setting options
        curl_setopt( $resCurl, CURLOPT_URL, self::DOMAIN. $strUri);
        curl_setopt( $resCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt( $resCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt( $resCurl, CURLOPT_SSL_VERIFYPEER, false);
        
        $strContent = null;

        // Setting method dependant options
        switch( $strMethod)
        {
            case 'GET':
                $intContentLength = null;
                $strContentMD5 = null;
            break;
            
            case 'POST':
                curl_setopt( $resCurl, CURLOPT_POST, true);
                curl_setopt( $resCurl, CURLOPT_POSTFIELDS, $strContent);
                $intContentLength = strlen( $strContent);
                $strContentMD5 = md5( $strContent);
            break;
            
            case 'PUT':
                curl_setopt( $resCurl, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt( $resCurl, CURLOPT_POSTFIELDS, $strContent);
                $intContentLength = strlen( $strContent);
                $strContentMD5 = md5( $strContent);
            break;
            
            case 'DELETE':
                curl_setopt( $resCurl, CURLOPT_CUSTOMREQUEST, 'DELETE');
                $intContentLength = strlen( $strContent);
                $strContentMD5 = md5( $strContent);
            break;
            
            default:
            break;
        }
        
        // building and setting headers
        $arrHeaders = array( 'Authorization: '. $this->_getAuthHeader( $strMethod, $strUri, $intContentLength, $strContentMD5),
                             'Content-Length: '. $intContentLength,
                             'Content-MD5: '. $strContentMD5);

        curl_setopt( $resCurl, CURLOPT_HTTPHEADER, $arrHeaders);
        
        // Making an API call
        $this->_strResponse = curl_exec( $resCurl);
        if ( $this->_strResponse === false)
            throw new Exception( 'Failed to make an SRP API call');
        else
            return curl_getinfo( $resCurl, CURLINFO_HTTP_CODE);
    }
    
    /**
     * Gets an API call response
     * 
     * @return string
     */
    public function getResponse()
    {
        return $this->_strResponse;
    }
}

// Retrieving id, name and provider for UK products 
$objApi = new ApiClient();
$intStatus = $objApi->call( 'GET', '/v1/products/products?market=MK0012&include=id,name,provider');

//if ( $intStatus !== 200)
//    echo 'Error occured. Status code is '. $intStatus;

header( 'Content-Type: text/xml');
echo $objApi->getResponse();


PHP chart

Script uses SRP API to fetch UK products, counts asset class popularity and using Google Charts API displays them in a pie.

<?php

class ApiClient
{
    /**
     * Domain name
     * 
     * @var string
     */
    const DOMAIN = 'http://api.structuredretailproducts.loc';
    
    /**
     * Public API key
     * 
     * @var string
     */
    const PUBLIC_API_KEY = '68uxlB048m2lEKwiuiWRAaBzxe3nwdfO';

    /**
     * Private API key
     * 
     * @var string
     */
    const PRIVATE_API_KEY = '68uxlB048m2lEKwiuiWRAaBzxe3nwdfO6N5aENMrEnz0hGw0uUw934ogaGC8U9OW';
    
    /**
     * Response
     * 
     * @var string
     */
    protected $_strResponse = null;
    
    /**
     * Builds auth header
     * 
     * @param string $strMethod
     * @param string $strUri
     * @param int $intContentLength
     * @param string $strContentMD5
     * @return string
     */
    protected function _getAuthHeader( $strMethod, $strUri, $intContentLength, $strContentMD5)
    {
        $intTimestamp = mktime();
        
        $strStringToSign = "$strMethod $strUri $intContentLength $strContentMD5 $intTimestamp";
        $strRawSignature = hash_hmac( 'sha1', $strStringToSign, self::PRIVATE_API_KEY, true);
        $strSignature = base64_encode( $strRawSignature);

        $strAuth = "SRP ". self::PUBLIC_API_KEY. ":$strSignature:$intTimestamp";
        
        return $strAuth;
    }
    
    /**
     * Makes an API call
     * 
     * @param string $strMethod
     * @param string $strUri
     * @return int status
     */
    public function call( $strMethod, $strUri)
    {
        $resCurl = curl_init();
        
        // Setting options
        curl_setopt( $resCurl, CURLOPT_URL, self::DOMAIN. $strUri);
        curl_setopt( $resCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt( $resCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt( $resCurl, CURLOPT_SSL_VERIFYPEER, false);
        
        $strContent = null;

        // Setting method dependant options
        switch( $strMethod)
        {
            case 'GET':
                $intContentLength = null;
                $strContentMD5 = null;
            break;
            
            case 'POST':
                curl_setopt( $resCurl, CURLOPT_POST, true);
                curl_setopt( $resCurl, CURLOPT_POSTFIELDS, $strContent);
                $intContentLength = strlen( $strContent);
                $strContentMD5 = md5( $strContent);
            break;
            
            case 'PUT':
                curl_setopt( $resCurl, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt( $resCurl, CURLOPT_POSTFIELDS, $strContent);
                $intContentLength = strlen( $strContent);
                $strContentMD5 = md5( $strContent);
            break;
            
            case 'DELETE':
                curl_setopt( $resCurl, CURLOPT_CUSTOMREQUEST, 'DELETE');
                $intContentLength = strlen( $strContent);
                $strContentMD5 = md5( $strContent);
            break;
            
            default:
            break;
        }
        
        // building and setting headers
        $arrHeaders = array( 'Authorization: '. $this->_getAuthHeader( $strMethod, $strUri, $intContentLength, $strContentMD5),
                             'Content-Length: '. $intContentLength,
                             'Content-MD5: '. $strContentMD5);

        curl_setopt( $resCurl, CURLOPT_HTTPHEADER, $arrHeaders);
        
        // Making an API call
        $this->_strResponse = curl_exec( $resCurl);
        if ( $this->_strResponse === false)
            throw new Exception( 'Failed to make an SRP API call');
        else
            return curl_getinfo( $resCurl, CURLINFO_HTTP_CODE);
    }
    
    /**
     * Gets an API call response
     * 
     * @return string
     */
    public function getResponse()
    {
        return $this->_strResponse;
    }
}

// Retrieving id, name and provider for UK products 
$objApi = new ApiClient();
$intStatus = $objApi->call( 'GET', '/v1/products/products?market=MK0012&include=id,asset_class');

if ( $intStatus !== 200)
    throw new Exception( 'Error occured. Status code is '. $intStatus);

// Processing data and counting asset class popularity
$objProducts = new SimpleXMLElement( $objApi->getResponse());
$arrAssetClasses = array();
foreach ( $objProducts->list->product as $objProduct)
    foreach ( $objProduct->asset_classes as $objAssetClass) 
    {
        $strCode = (string) $objAssetClass->asset_class->code;
        $strName = (string) $objAssetClass->asset_class->name;
        if ( ! isset( $arrAssetClasses[$strCode])) 
            $arrAssetClasses[$strCode] = array( $strName, 1);
        else
            $arrAssetClasses[$strCode][1] = $arrAssetClasses[$strCode][1] + 1;
    }

// preparing data for chart
$arrData = json_encode( array_values( $arrAssetClasses));

// further script uses google charts API to display our data in a pie chart
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Asset class');
        data.addColumn('number', 'Popularity');
        data.addRows(<?php echo $arrData; ?>);
        var options = { title: 'Popularity of asset classes in UK'};

        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>