Unauthorized (401) error using Data API

Jump to solution
kj460
Community Novice

Hi all,

I'm trying to create a function in python that allows me to connect to the Data API, but for some every time I tried to request something it returns the 401 Unauthorized error message.

I followed one of the examples listed on this page (Canvas Data API Authentication ) to test that my function and I confirmed that it generates the correct header for the requests.

I slightly modified the sample function provided by  @dpassey ‌ on An actual WORKING Canvas Data script in Python page and below is my function.

Thank you in advance

apiMethod = 'GET'
apiHost = 'portal.inshosteddata.com'
apiContentType = ''
apiMD5 = ''
apiPath = '/api/account/self/dump'
apiQueryParam = ''
apiTime = datetime.utcnow().strftime('%a, %d %b %y %H:%M:%S GMT')

# building a message; 8 parameters in order
msgList = []
msgList.append(apiMethod)
msgList.append(apiHost)
msgList.append(apiContentType)
msgList.append(apiMD5)
msgList.append(apiPath)
msgList.append(apiQueryParam)
msgList.append(apiTime)
msgList.append(secret)
# separate each parameter with newline ('\n')
msgStr = bytes("".join("%s\n" % k for k in msgList).strip(), 'utf-8')

# create encoded hash signature; use HMAC-SHA-256 and encode with base64
sig = base64.b64encode(hmac.new(key=bytes(secret, 'utf-8'), msg=msgStr, digestmod=hashlib.sha256).digest())
sig = sig.decode('utf-8')

# generate headers; response will be in JSON format
headers = {}
headers['Authorization'] = 'HMACAuth {}:{}'.format(key, sig)
headers['Date'] = apiTime
headers['Content-type'] = apiContentType

r = requests.get('https://' + apiHost + apiPath, headers=headers)
if r.status_code == 200:
printt('success')
else:
printt(r.text)
0 Likes
1 Solution
kj460
Community Novice
Author

There was nothing wrong with the code.

With newly generated keys, the above code returned what I was expecting to get.

View solution in original post

0 Likes