Discourse API Uploads

Hello!

I have a question about how I can using Python3 upload a file. I tried to do something like that, but I still get error.

> import requests
headers = {
    'content-type': 'multipart/form-data', #application/x-www-form-urlencoded ??
    'Api-Key': 'MyWorkingKey',
    'Api-Username': 'discourseAdmin',
}
URL = "https://discourse.com/uploads.json"
content = open('FULL_PATH_TO/avatar.jpg', 'rb').read()
data={"type": "avatar",'files[]': ('avatar.jpg', content, 'image/jpeg')}
requests.post(URL, headers=headers, data=data)

*Status Code: 422*
*Response TExt: '{"failed":"FAILED","message":"undefined method `tempfile\' for \\"avatar.jpg\\":String"}'*

I did upload the file via this curl:

curl -X POST https://discourse.com/uploads.json \
-H "content-type: multipart/form-data;" \
-H "Api-Key: MyWorkingKey" \
-H "Api-Username: discourseAdmin" \
-F "type=avatar" \
-F "files[]=@FULL_PATH_TO/avatar.jpg"

Unfortunately, I did not successfully move this curl command into Python.

1 Like

This worked for me:

r = requests.post(f'{rooturl}/uploads.json',
                  files = {'files[]': (file, open(file, 'rb'), 'image/png')},
                  data={'type':'image'},
                  headers={
                      "Api-Username" : sys.argv[1],
                      "Api-Key" : sys.argv[2],
                  })

Probably, content-type': 'multipart/form-data' should be omitted so the requests library can figure out what to.

4 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.