File Uploads using Python

I was able to successfully upload a file to a column using the following python code, using the requests library. Fair warning, here be dragons.

item_id = 12345678 #example only
f = 'file-path/file-name.ext'
q = f"""
        mutation add_file($file: File!) {{
            add_file_to_column (item_id: {int(item_id)},
                        column_id: files,
                        file: $file
                    ){{
                id
            }}
        }}
    """
    
files = {
    'query': (None, q, 'application/json'),
    'variables[file]': (f, open(f, 'rb'), 'application/octet-stream', {'Content-Transfer-Encoding': 'binary'})
}
r = requests.post(
    url='https://api.monday.com/v2/file',
    headers=headers,
    files=files
)

One thing worth noting is you cannot pass other variables to the request, if you are also passing a file. I had to use string interpolation in order to pass the item_id to make it work.

I was also able to reproduce this issue in JavaScript as well.

Though my issue was worked around, I would be interested to know why this issue exists. Is this expected behavior according to the spec?

Hey @hamptonpaulk :wave:

Thanks for reaching out here and I’m sorry to hear uploading files has given you some trouble here. To be transparent with you, you can indeed use multiple variables when making the call, but youwill need to construct the request slightly differently. I’ve made a couple of guides you could reference on this as well:

Using Variables in File Uploads - NodeJS
Uploading files with variables

Let me know if this helps :slight_smile:

-Alex

Thanks for your reply, but those methods did not work when implemented in python using the requests library. Do you have code, in python, that accomplished this? I also attempted the postman example as well with no luck. I spent quite some time reviewing your older posts and other languages to no avail, before I posted this.

@hamptonpaulk

Sorry for the delay on this! I would love to troubleshoot your Postman setup! Could you please provide a screenshot of the way you are currently trying to send files with variables in Postman?

In the meantime, here’s the code Postman provides as the Python equivalent of the example I’ve used:

import requests

url = "https://api.monday.com/v2/file"

payload={'query': 'mutation add_file($file: File!, $update_id: Int!) {add_file_to_update(update_id: $update_id, file: $file) {id}}',

'variables': '{"update_id":967485603}',

'map': '{"image":"variables.file"}'}

files=[

('image',('300px-All_Right_Then,_Keep_Your_Secrets.jpg',open('/Users/alexsavchuk/Downloads/300px-All_Right_Then,_Keep_Your_Secrets.jpg','rb'),'image/jpeg'))

]

headers = {

'Authorization': 'YourAPIKey',
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)