0

I got the Report Id and using the Report Id i could get S3 Downloadable link. But when i try to use the link it shows - Access Unauthorised.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Prasand Kumar
  • 145
  • 1
  • 7
  • Are you supplying the client ID, scope, and access key? https://advertising.amazon.com/API/docs/en-us/sponsored-products/2-0/openapi#/Reports/getReport example of your code would be helpful. – mr_mooo_cow Mar 15 '21 at 20:22

2 Answers2

2

You need to do a GET request against the download link. The URL requires authentication as well, so the authorization header must be passed too.

Edit I am adding a function that I created that downloads the GZipped file and extracts the Json in it, in case it helps anyone else:

import requests
import gzip
import json
import io

def report_download():
    req = requests.get(url, headers=headers)
    response = req.content
    zip_file = io.BytesIO(response)
    with gzip.open(zip_file, 'rb') as f: 
        file_content = f.read() 

    json_data = json.loads(file_content)
    with open("filename.json", "w") as outfile: 
        json.dump(json_data, outfile)
0

Here's an easy way to download the report with python and pandas

def api_download_report_resp(access_token, profile_id, report_id):
    url = f"https://advertising-api.amazon.com/v2/reports/{report_id}/download"
    client_id = os.getenv("AMAZON_ADS_API_CLIENT_ID")
    
    with requests.Session() as sess:
        sess.headers["Amazon-Advertising-API-ClientId"] = client_id
        sess.headers["Amazon-Advertising-API-Scope"] = profile_id
        sess.headers["Authorization"] = f"Bearer {access_token}"
        sess.headers["Content-Type"] = "application/json"
        resp = sess.get(url)
    
    return resp

resp = api_download_report_resp(access_token, profile_id, report_id)
print(resp)
# <Response [200]>

import pandas as pd
import io

fobj = io.BytesIO()
fobj.write(resp.content)
fobj.seek(0)
df = pd.read_json(fobj, compression='gzip')
Alex
  • 12,078
  • 6
  • 64
  • 74