fernandosjp
fernandosjp

Reputation: 2778

How can I use Canvas Data REST API using python?

The organization I work for is starting to use Canvas LMS and I was in charged of pulling out the platform's data and in order to help with data insights.

It's great that Canvas LMS offers a Data API but I had a hard time fiding a Python wrapper to use. I wanted to interact with it using Python which is part of our official stack here.

I know there is the official documentation in (https://portal.inshosteddata.com/docs/api) but I'm not really used with the authorization method and it would be so much easier to have a sample code.

So, how should I start my python code to interact with the Canvas LMS Data API?

Upvotes: 7

Views: 2690

Answers (1)

fernandosjp
fernandosjp

Reputation: 2778

Here we go!

I finally got it done with the help of the Canvas community through their website (https://community.canvaslms.com/thread/7423). I'm also posting question and answer here because I believe StackOverflow is easier to find answers.

Hope this will be useful to someone else!

#!/usr/bin/python

#imports
import datetime
import requests
import hashlib
import hmac
import base64
import json


#Get the current time, printed in the right format
def nowAsStr():
  currentTime = datetime.datetime.utcnow()
  prettyTime = currentTime.strftime('%a, %d %b %Y %H:%M:%S GMT')
  return prettyTime

#Set up the request pieces
apiKey = 'your_key'
apiSecret = 'your_secret'
method = 'GET'
host = 'api.inshosteddata.com'
path = '/api/account/self/dump'
timestamp = nowAsStr()

requestParts = [
  method,
  host,
  '', #content Type Header
  '', #content MD5 Header
  path,
  '', #alpha-sorted Query Params
  timestamp,
  apiSecret
]

#Build the request
requestMessage = '\n'.join(requestParts)
print (requestMessage.__repr__())
hmacObject = hmac.new(apiSecret, '', hashlib.sha256)
hmacObject.update(requestMessage)
hmac_digest = hmacObject.digest()
sig = base64.b64encode(hmac_digest)
headerDict = {
  'Authorization' : 'HMACAuth ' + apiKey + ':' + sig,
  'Date' : timestamp
}

#Submit the request/get a response
uri = "https://"+host+path
print (uri)
print (headerDict)
response = requests.request(method='GET', url=uri, headers=headerDict, stream=True)

#Check to make sure the request was ok
if(response.status_code != 200):
  print ('Request response went bad. Got back a ', response.status_code, ' code, meaning the request was ', response.reason)
else:
  #Use the downloaded data
  jsonData = response.json()
  print json.dumps(jsonData, indent=4)

Upvotes: 9

Related Questions