roshanoracle
10/25/2019 - 3:15 PM

DMP Bulk API Sample Call

import os
import sys
import urllib
import urllib2
import cookielib
import urlparse
import hashlib 
import hmac
import base64
import json
import random

# 1. Enter your BlueKai developer keys

bkuid = 'ENTER PUBLIC KEY' #Web Service User Key
bksecretkey = 'ENTER SECRET KEY' #Web Service Private Key

# 2.  Other Details

siteID = 'XXXXX' # Insert site ID
responseCallBackUrl = "http://myendpoint.com" # Endpoint to send call results
responseType = "Detail" # "Detail", "Summary" or None"

# PUUIDs - queue up your IDs here

# NOTE THAT THIS SCRIPT GENERATES THE SAME DATA PER PUUID HERE AS IT'S JUST A WAY OF TESTING

puuids  = []
puuids.append('puuid1') #Enter in a PUUID here you want to test
puuids.append('puuid2') #Enter in a PUUID here you want to test (repeat for more)

# Set pfield for 'puuid'
pfield = 'test' #optional - leave as '' if not sure. Not sure why you need this sometimes - this is the phint name, e.g. 'customer_id' the PUUID is collected on, e.g. phint=customer_id=VALUE

# Set phint(s) string
phints = 'phint=pageID%3DHome' # For testing, we'll just send a standard phint string per ID

# DO NOT EDIT BELOW THIS LINE
# DO NOT EDIT BELOW THIS LINE
# DO NOT EDIT BELOW THIS LINE
# DO NOT EDIT BELOW THIS LINE

if pfield:
	pfield_string = "&pfield=" + pfield
	
else:
	pfield_string = ""

headers = {

    "ApiKey" : bkuid,
    "Accept" : "application/json",
    "Content-Type" : "application/json"
}


Url = "https://bulkapi.bluekai.com/2/api"

# 3. For POST and PUT requests, uncomment the "data" variable and enter the JSON body
data = {}
data["Method"] = "POST"
data["ResponseCallbackUrl"] = responseCallBackUrl
data["ResponseType"] = responseType
data["Scatter"] = []


# Loop through IDs to batch up API calls

for puuid in puuids:

    print "BATCHING API CALL : siteid=",siteID,"|",pfield_string,"|puuid=",puuid,"|",phints,"\n"    

    data["Scatter"].append({
        "Method": "POST",
        "URIPath": "/getdata/" + siteID + "/v1.2?bkuid=" + bkuid + "&puserid=" + puuid + pfield_string + "&" + phints,
        "RequestID": puuid
    })


#Creating the method signature
def signatureInputBuilder(url, method, data):

    #print stringToSign
    if data != None :
        
        print "\nPRE-SIGNING : data\n"
        print data

        stringData = json.dumps(data)
        #stringData = json.dumps(data,separators=(',', ':'))

        stringToSign = stringData 
        #stringToSign += data 

    print "\nString to be Signed:\n" + stringToSign
    
    h = hmac.new(bksecretkey, stringToSign, hashlib.sha256)

    s = base64.standard_b64encode(h.digest())
    print "\nRaw Method Signature:\n" + s 
    
    u = urllib.quote_plus(s)
    print "\nURL Encoded Method Signature (bksig):\n" + u

    newUrl = url 
    if url.find('?') == -1 :
        newUrl += '?'
    else:
        newUrl += '&'
        
    #newUrl += 'bkuid=' + bkuid + '&bksig=' + u 
    #newUrl += 'bksig=' + s
    newUrl += 'bksig=' + u 
    

    return newUrl

#Generating  the method request 
def doRequest(url, method, data):
    print "\nFUNCTION CALLED : doRequest\n"
    try:
        cJ = cookielib.CookieJar()
        request = None
        if method == 'PUT': 
            request = urllib2.Request(url, data, headers)
            request.get_method = lambda: 'PUT'
        elif  method == 'DELETE' :
            request = urllib2.Request(url, data, headers)
            request.get_method = lambda: 'DELETE'
        elif data != None :            
            print "Calling API now...\n"
            #formatted_data = json.dumps(data,separators=(',', ':'))
            formatted_data = json.dumps(data)
            print "URL:"
            print url
            print "\nHeaders:"
            print headers
            print "\nData:"
            print formatted_data

            
            request = urllib2.Request(url, formatted_data, headers)
            #request = urllib2.Request(url, data=formatted_data,headers=headers)
            #request = urllib2.Request("https://fozysf7tnf.execute-api.eu-west-1.amazonaws.com/prod", data=formatted_data,headers=headers)
            #request = urllib2.Request("https://fozysf7tnf.execute-api.eu-west-1.amazonaws.com/prod", data=formatted_data,headers=headers)                        
            response = urllib2.urlopen(request)            
            response_text = response.read()        
            print "Response received. See below:"            
            print response_text
            
        else:
            print "\nCalling API now...\n"
            request = urllib2.Request(url, None, headers)  
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cJ))
            u = opener.open(request)
            rawData = u.read()
            print "\nResponse Code: 200"
            print "\nAPI Response:\n\n" + rawData
            return rawData

    except urllib2.HTTPError, e:
        print "\nHTTP error: %d %s" % (e.code, str(e)) 
        print "ERROR: ", e.read()
        return None
    except urllib2.URLError, e:
        print "Network error: %s" % e.reason.args[1]
        print "ERROR: ", e.read()
        return None

#4. Specify the API request method 
def main(argv=None):
    
    # Select the API Method by uncommenting the newUrl reference variable and doRequest() method
    
    # GET
    #newUrl = signatureInputBuilder(Url, 'GET', None)
    #print "API Call: \n" + newUrl
    #doRequest(newUrl, 'GET', None)
    
    # POST
    newUrl = signatureInputBuilder(Url, 'POST', data)
    print "\nAPI Call: \n" + newUrl
    doRequest(newUrl, 'POST', data)    
    
    # PUT
    #newUrl = signatureInputBuilder(Url, 'PUT', data)
    #doRequest(newUrl, 'PUT', data)
    
    #DELETE
    #newUrl = signatureInputBuilder(Url, 'DELETE', None)
    #doRequest(newUrl, 'DELETE', None)
    
    

if __name__ == "__main__":
   main()