AnsweredAssumed Answered

Upload files to Canvas using Python

Question asked by Alessandro Mottura on Jun 10, 2017
Latest reply on Jan 14, 2018 by Patrick Tam

Hi,

I am trying to write a Python script to upload a file to course files in Canvas using the API. I have followed the API tutorial (Uploading Files - Canvas LMS REST API Documentation). Unfortunately I get stuck on Step 2. I have looked through past questions, but could not find anything similar.

import requests

# Access token and API url
access_token = 'insert token here'
api_url = 'https://canvas.bham.ac.uk/api/v1/courses/22416/files'

# Set up a session
session = requests.Session()
session.headers = {'Authorization': 'Bearer %s' % access_token}

# Step 1 - tell Canvas you want to upload a file
payload = {}
payload['name'] = 'test.pdf'
r = session.post(api_url, data=payload)
r.raise_for_status()
r = r.json()
print ' '
print r # This successfully returns the expected response...

# Step 2 - upload file
payload = list(r['upload_params'].items()) # Note this is now a list of tuples
print ' '
print payload
with open('test.pdf', 'rb') as f:
     file_content = f.read()
payload.append((u'file', file_content)) # Append file at the end of list of tuples
r = session.post(r['upload_url'], data=payload)
r.raise_for_status() # This returns 400 Client Error: Bad Request
print ' '
print r

I probably want to say a few extra details about Step 2. On line 21, I convert the upload_params dictionary to a list of tuple because the file upload tutorial says the file should be added at the end of the upload_params...and dictionaries in Python are not ordered. I assume this is ok. The code stops on line 28, as line 27 returns a 400 Client Error. I have not written code for Step 3 as I cannot move past Step 2.

Any ideas?

Thanks for your help!

Alessandro

Outcomes