This article presents two workflows in Python. (Click here to download Python 3.8.)
Example
import json import urllib.request from urllib.error import HTTPError import time null = None # Configurations. Please change these accordingly. isProd = True SASPlatformUsername = "UserName" SASPlatformPassword = "UserPassword" SASPlatformAPIkey = "API KEY" APIObject = { "entities": [{ "type": "AnalyticsReport", "reportName": "test", "reportScope": { "entitiesHierarchy": { "entitiesHierarchyLevelType": "ACCOUNT", "accounts": [8804], "advertisers": [], "campaigns": [], "sites": [] }, "attributionModelID": 0, "impressionCookieWindow": 0, "clickCookieWindow": 0, "filters": {}, "currencyOptions": { "type": "Custom", "defaultCurrency": 1, "targetCurrency": 1, "currencyExchangeDate": "2019-12-24" }, "timeRange": { "timeZone": "Greenwich", "type": "Custom", "dataStartTimestamp": "2019-12-23T00:00:00.000Z", "dataEndTimestamp": "2019-12-23T23:59:59.999Z" }, "presetId": null }, "reportStructure": { "attributeIDs": ["Account ID"], "metricIDs": ["Served Impressions"], "attributeIDsOnColumns": [], "timeBreakdown": "Day" }, "reportExecution": { "type": "Ad_Hoc" }, "reportDeliveryMethods": [{ "type": "URL", "exportFileType": "JSON", "compressionType": "NONE", "emailRecipients": ["Jane.Smith@sizmek.com"], "exportFileNamePrefix": "test" }], "reportAuthorization": { "type": "mm3", "userID": 1234567890 } }] } # First, retrieve the authorization token from the SAS platform UATUrl = 'https://adapi.uat.sizmek.com' ProdUrl= 'https://adapi.sizmek.com' loginAPIendpoint = '/sas/login/login' loginUrl = (ProdUrl+loginAPIendpoint) if isProd else (UATUrl+loginAPIendpoint) payload = {"username":SASPlatformUsername, "password":SASPlatformPassword} params = json.dumps(payload).encode('utf8') req = urllib.request.Request(loginUrl, data=params, headers={'content-type': 'application/json', 'api-key':SASPlatformAPIkey})response = urllib.request.urlopen(req) decodedResponse = response.read().decode('utf8') responseAsJson = json.loads(decodedResponse) authToken = responseAsJson["result"]["sessionId"] # Then, use the Report Builder API to create a report APIObjectAsJson = json.dumps(APIObject).encode('utf8') saveAndExecUrlUAT = "https://api.uat.dev.sizmek.com/rest/ReportBuilder/reports/saveAndExecute" saveAndExecUrlProd = "https://api.sizmek.com/rest/ReportBuilder/reports/saveAndExecute" saveAndExecUrl = saveAndExecUrlProd if isProd else saveAndExecUrlUAT req = urllib.request.Request(saveAndExecUrl, data=APIObjectAsJson, headers={'Authorization': authToken,'content-type': 'application/json'}) response = urllib.request.urlopen(req) responseAsJson = json.loads(response.read().decode('utf8')) executionID = responseAsJson["result"]["executionID"] print("executionID: " + executionID) # Finally, query the Report Builder API every few minutes to check if your report is available getExecutionUrlUAT = "https://adapi.uat.sizmek.comuat.dev.sizmek.com/rest/ReportBuilder/reports/executions/"+executionID getExecutionUrlProd = "https://adapi.sizmek.comapi.sizmek.com/rest/ReportBuilder/reports/executions/"+executionID getExecutionUrl = getExecutionUrlProd if isProd else getExecutionUrlUAT timeoutSec = 20*60 sleepTimeSec = 0 sleepForSec = 2*60 while(sleepForSec <= timeoutSec): req = urllib.request.Request(getExecutionUrl, headers={'Authorization': authToken,'content-type': 'application/json'}) response = urllib.request.urlopen(req) responseAsJson = json.loads(response.read().decode('utf8')) if(responseAsJson["result"]["executionStatus"] == "FINISHED"): print("\nThe report finished successfully") print(responseAsJson) break else: print("The report is not ready yet. Sleeping for " + str(sleepForSec) + "seconds...") print("Total waiting time is: " + str(sleepTimeSec/60) + " minutes\n") print(responseAsJson) sleepTimeSec = sleepTimeSec + sleepForSec time.sleep(sleepForSec) if(sleepForSec > timeoutSec): print("Error: Timeout reached. Waited for " + str(sleepTimeSec/60) + " minutes but the report is still not ready! Exiting...") else: print("\nDownload link: " + responseAsJson["result"]["files"][0]["url"])
Example
import json import urllib.request null = None # Configurations. Please change these accordingly. isProd = True SASPlatformUsername = "UserName" SASPlatformPassword = "UserPassword" SASPlatformAPIkey = "API KEY" APIObject = { "entities": [{ "type": "AnalyticsReport", "reportName": "test", "reportScope": { "entitiesHierarchy": { "entitiesHierarchyLevelType": "ACCOUNT", "accounts": [8804], "advertisers": [], "campaigns": [], "sites": [] }, "attributionModelID": 0, "impressionCookieWindow": 0, "clickCookieWindow": 0, "filters": {}, "currencyOptions": { "type": "Day of report generation", "defaultCurrency": 1, "targetCurrency": 1 }, "timeRange": { "type": "Yesterday", "timeZone": "Greenwich" }, "presetId": null }, "reportStructure": { "attributeIDs": ["Account ID"], "metricIDs": ["CTR", "Total Clicks", "Served Impressions"], "attributeIDsOnColumns": [], "timeBreakdown": "Day" }, "reportExecution": { "type": "Scheduled", "startTimestamp": "2020-06-07T21:00:00.000Z", "cronExpression": "0 0 4* * ? *", "endTimestamp": "2020-06-11T20:59:00.000Z", "timeZone": "Greenwich" }, "reportDeliveryMethods": [{ "type": "URL", "exportFileType": "JSON", "compressionType": "NONE", "emailRecipients": ["Jane.Smith@sizmek.com"], "exportFileNamePrefix": "test" }], "reportAuthorization": { "type": "mm3", "userID": 1234567890 } }] } # First, retrieve the authorization token from the SAS platform UATUrl = 'https://adapi.uat.sizmek.com' ProdUrl= 'https://adapi.sizmek.com' loginAPIendpoint = '/sas/login/login' loginUrl = (ProdUrl+loginAPIendpoint) if isProd else (UATUrl+loginAPIendpoint) payload = {"username":SASPlatformUsername, "password":SASPlatformPassword} params = json.dumps(payload).encode('utf8') req = urllib.request.Request(loginUrl, data=params, headers={'content-type': 'application/json', 'api-key':SASPlatformAPIkey}) response = urllib.request.urlopen(req) decodedResponse = response.read().decode('utf8') responseAsJson = json.loads(decodedResponse) authToken = responseAsJson["result"]["sessionId"] # Then, use the Report Builder API to create a scheduled reportAPIObjectAsJson = json.dumps(APIObject).encode('utf8') saveAndActivateUrlUAT = "https://api.uat.dev.sizmek.com/rest/ReportBuilder/reports/saveAndActivate" saveAndActivateUrlProd = "https://api.sizmek.com/rest/ReportBuilder/reports/saveAndActivate" saveAndActivateUrl = saveAndActivateUrlProd if isProd else saveAndActivateUrlUAT req = urllib.request.Request(saveAndActivateUrl, data=APIObjectAsJson, headers={'Authorization': authToken,'content-type': 'application/json'}) response = urllib.request.urlopen(req) responseAsJson = json.loads(response.read().decode('utf8')) print("Report has been scheduled successfully") print("reportID: " + responseAsJson["result"]["reportID"])
Comments