pythonpython-3.xamazon-advertising-api

Trying to Retrieve Report from Amazon Ads API


I am trying to retrieve a report that I generated, and shows a 'status' of 'successful'.

When I run the script below, I receive a 200 response. However, per the docs:

"A successful call returns a 307 redirect response. The redirect link points you to the S3 bucket where you can download your report file. The report file downloads as JSON compressed in gzip format."

headers = {
    'Amazon-Advertising-API-ClientId': clientid,
    'Authorization': access,
    'Amazon-Advertising-API-Scope':scope,
    'Content-Type':'application/json'
}
    
response = requests.get(
  'https://advertising-api.amazon.com/v1/reports/amzn1.clicksAPI.v1.p1.624466CD.4b8dcbb2-bbc6-4936-a760-c632216a4a5e/download',
  headers = headers
)
    
print(response.json)

response:

<bound method Response.json of <Response [200]

Solution

  • import gzip  # unzip compressed file
    import io  # read binary
    import requests
    import pandas as pd
    
    headers = {
        "Authorization": f"Bearer {access_code}",
        "Amazon-Advertising-API-Scope": profile_id,
        "Amazon-Advertising-API-ClientId": client_id
    }
    
    response = requests.get(report_url, headers=headers)
    
    if response.ok:
        json_resp = response.json()
        status = json_resp['status']
        if status == 'IN_PROGRESS':
            # check again
        elif status == 'SUCCESS':
            # initiate download
            location = json_resp['location']
            dl_response = requests.get(location, headers=headers, allow_redirects=True)
            if dl_response.ok:
                compressed_file = io.BytesIO(response.content)  # extract .gz file
                decompressed_file = gzip.GzipFile(fileobj=compressed_file)  # unzip .gz file
                output = pd.read_json(decompressed_file)
        elif status == 'FAILURE':
            # failure response