How To and Samples

From SRP API Docs

How To and Samples

Authentication

PHP

To create HMAC-SHA1 signature you can use:

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

JAVA

To create HMAC-SHA1 signature you can use:

	
String strPrivateApiKey = "YOUR_PUBLIC_API_KEY";
String strUri = "/v1/products?market=MK0012" ;
String strContentLength = "";
String strContentMD5 = "";
long lngTimestamp = System.currentTimeMillis() / 1000L;
String strStringToSign = "GET " + strUri + " " + strContentLength + " "+ strContentMD5 + " " + lngTimestamp;


String keyString = "YOUR_PRIVATE_API_KEY";
SecretKey secretKey = null;
byte[] keyBytes = keyString.getBytes();
secretKey = new SecretKeySpec(keyBytes, "hmacSha1");
Mac mac = Mac.getInstance("hmacSha1");
mac.init(secretKey);

byte[] text = strStringToSign.getBytes();
String strSignature = new String(Base64.encodeBase64(mac.doFinal(text))).trim();
String strAuth = "SRP " + strPrivateApiKey + ":" + strSignature + ":" + lngTimestamp;

Client

PHP simple XML list

Simple API client using cUrl library.

<?php

class ApiClient
{
    /**
     * Domain name
     * 
     * @var string
     */
    const DOMAIN = 'https://api.structuredretailproducts.com';
    
    /**
     * Public API key
     * 
     * @var string
     */
    const PUBLIC_API_KEY = 'YOUR_PUBLIC_API_KEY';

    /**
     * Private API key
     * 
     * @var string
     */
    const PRIVATE_API_KEY = 'YOUR_PRIVATE_API_KEY';
    
    /**
     * 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 full product details for product with id 4079750
// NOTE: if you are fetching by Product ID, make sure you have access to the market

$objApi = new ApiClient();
$intStatus = $objApi->call( 'GET', '/v1/products/products?id=ID04079750');

//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 a pie chart format.

<?php

class ApiClient
{
    /**
     * Domain name
     * 
     * @var string
     */
    const DOMAIN = 'https://api.structuredretailproducts.com';
    
    /**
     * Public API key
     * 
     * @var string
     */
    const PUBLIC_API_KEY = 'YOUR_PUBLIC_API_KEY';

    /**
     * Private API key
     * 
     * @var string
     */
    const PRIVATE_API_KEY = 'YOUR_PRIVATE_API_KEY';
    
    /**
     * 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 and asset class 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>

Output:

Asset classes pie.jpg

Java XML lists


import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Base64;

class ApiClient {

	/**
	 * Domain name
	 * 
	 */
	final String DOMAIN = "https://api.structuredretailproducts.com";

	/**
	 * Public API key
	 * 
	 */
	final String PUBLIC_API_KEY = "YOUR_PUBLIC_API_KEY";

	/**
	 * Private API key
	 * 
	 */
	final String PRIVATE_API_KEY = "YOUR_PRIVATE_API_KEY";

	/**
	 * SHA1 Sign the string
	 * 
	 * @param baseString
	 *            base string to be singed
	 * @return signed string with private key
	 * @throws Exception
	 */
	public String _hmacSha1(String baseString) throws Exception {

		String keyString = this.PRIVATE_API_KEY;
		SecretKey secretKey = null;

		byte[] keyBytes = keyString.getBytes();
		secretKey = new SecretKeySpec(keyBytes, "hmacSha1");

		Mac mac = Mac.getInstance("hmacSha1");

		mac.init(secretKey);

		byte[] text = baseString.getBytes();

		return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
	}

	/**
	 * 
	 * @param strUri
	 * @param strContentLength
	 * @param strContentMD5
	 * @return
	 * @throws Exception
	 */
	protected String _getAuthHeader(String strUri, String strContentLength,
			String strContentMD5) throws Exception {

		long lngTimestamp = System.currentTimeMillis() / 1000L;
		String strStringToSign = "GET " + strUri + " " + strContentLength + " "
				+ strContentMD5 + " " + lngTimestamp;
		String strSignature = this._hmacSha1(strStringToSign);
		String strAuth = "SRP " + this.PUBLIC_API_KEY + ":" + strSignature
				+ ":" + lngTimestamp;
		return strAuth;
	}

	/**
	 * 
	 * @param strUri
	 * @return
	 */
	public String fetch(String strUri) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(this.DOMAIN + strUri);

			// for a get request strContentLength,strContentMD5 are always empty string, DO NOT use null,
			// it will create a wrong signature key
			
			request.setHeader("Authorization", this._getAuthHeader(strUri,"",""));

			HttpResponse response = client.execute(request);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			StringBuilder builder = new StringBuilder();
			String aux = "";

			while ((aux = reader.readLine()) != null) {
				builder.append(aux);
			}

			return builder.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Run the sample
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			ApiClient api = new ApiClient();
			
			String xmlResponse = null;
			
			/**
			 *  NOTE: no matter what combination of filter you use, you will only get results from allowed markets.
			 *  @see http://wiki.structuredretailproducts.com/index.php/Reference_Guide_-_Product_filters for list of filters and how to use them,
			 *  to find the list of filer properties see column "Possible values" 
			 */
			
			// Fetching single product, make sure product listed under one one of allowed markets
			xmlResponse = api.fetch("/v1/products/products?id=ID04079750");
			System.out.println(xmlResponse);
			
			
			// Fetching all UK products
			xmlResponse = api.fetch("/v1/products/products?market=MK12");
			System.out.println(xmlResponse);
			
			// Fetching all UK Commodities
			xmlResponse = api.fetch("/v1/products/products?asset_class=AC10&market=MK12");
			System.out.println(xmlResponse);
			
			// Fetching all Eurostoxx50 products striking in 2012.
			xmlResponse = api.fetch("/v1/products/products?initial_strike=2012-01-01,2012-12-31&underlying=UD00009");
			System.out.println(xmlResponse);


		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

C# XML lists

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace SrpAPi
{
    public class ApiClient
    {

        /// <summary>
        /// Domain name
        /// </summary>
        private const string DOMAIN = "https://api.structuredretailproducts.com";

        /// <summary>
        /// Public API key
        /// </summary>

        private const string PUBLIC_API_KEY = "YOUR_PUBLIC_API_KEY";
        /// <summary>
        /// Private API key
        /// </summary>
        private const string PRIVATE_API_KEY = "YOUR_PRIVATE_API_KEY";

        /// <summary>
        /// Return seconds since 1st Jan, 1970
        /// </summary>
        /// <returns></returns>

        private long GetTimestamp()
        {
            DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds / 1000L;
        }


        /// <summary>
        /// SHA1 Sign the string
        /// </summary>
        /// <param name="textToEncode"></param>
        /// <returns></returns>

        public string hmacSha1(string textToEncode)
        {
            HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(PRIVATE_API_KEY));

            byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(textToEncode));

            return Convert.ToBase64String(hash).Trim();
        }
        /// <summary>
        /// Return Auth header
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="contentLength"></param>
        /// <param name="contentMD5"></param>
        /// <returns></returns>
        private string GetAuthHeader(string uri, string contentLength, string contentMD5)
        {
            long timestamp = GetTimestamp();
            String stringToSign = "GET " + uri + " " + contentLength + " " + contentMD5 + " " + timestamp;
            string signature = hmacSha1(stringToSign);
            string auth = "SRP " + PUBLIC_API_KEY + ":" + signature + ":" + timestamp;

            return auth;
        }
        /// <summary>
        /// Make HTTP request and return response as XML string.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        private string Fetch(string uri)
        {
            HttpWebRequest request = WebRequest.Create(DOMAIN + uri) as HttpWebRequest;

            request.Method = "GET";
            request.Headers["Authorization"] = GetAuthHeader(uri, "", "");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream receiveStream = response.GetResponseStream();

            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            return readStream.ReadToEnd();
        }
        
        /// <summary>
        /// Run sample requests
        /// </summary>
        static void Main()
        {

            ApiClient api = new ApiClient();

            String xmlResponse = null;

            /// <summary>
            /// NOTE: no matter what combination of filter you use, you will only get results from allowed markets.
            /// @see http://wiki.structuredretailproducts.com/index.php/Reference_Guide_-_Product_filters for list of filters and how to use them,
            /// to find the list of filer properties see column "Possible values" 
            /// </summary>           

           
            /// Fetching single product, make sure product listed under one one of allowed markets
            xmlResponse = api.Fetch("/v1/products/products?id=ID04079750");
            Console.WriteLine(xmlResponse);


            /// Fetching all UK products
            ///xmlResponse = api.Fetch("/v1/products/products?market=MK12");
            ///Console.WriteLine(xmlResponse);

            /// Fetching all UK Commodities
            ///xmlResponse = api.Fetch("/v1/products/products?asset_class=AC10&market=MK12");
            ///Console.WriteLine(xmlResponse);

            /// Fetching all Eurostoxx50 products striking in 2012.
            xmlResponse = api.Fetch("/v1/products/products?initial_strike=2012-01-01,2012-12-31&underlying=UD00009");
            Console.WriteLine(xmlResponse);
            Console.ReadKey();
        }
    }
}