Using Python to upload avatar (Discourse API)

Hello :wave:,

I’ve read these helpful posts (1, 2); however, I’m still missing something that is preventing me from successfully uploading an avatar from Python to Discourse using the API. I am the admin of my Discourse site.

The good news: It works in Postman as shown below.

The not so good news: I haven’t been able to translate this to Python (getting 400 or 422 errors, depending on what I attempt). I’ve tried the following:

img_data = requests.get("my_image_url").content

data={
"type": "avatar",
"user_id": user_id,
"synchronous": True,
"file":  img_data
}

url = "<my site>/uploads.json"

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

This gives me a 400 error. I’ve also tried using a local image just to see if I could get it to work:

with open('my_local_image.jpg', "rb") as f:
    image_b64 = base64.b64encode(f.read()).decode("utf8")

data={
"type": "avatar",
"user_id": user_id,
"synchronous": True,
"file":  image_b64
}

url = "<my site>/uploads.json"

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

This gives me a 422 error:

"failed":"FAILED","message":"undefined method `tempfile\' for #\\u003cString:0x00007f5befda7af8\\u003e"

:pray: I feel like I am close but I’m somewhat new to using API. Any pointer in the right direction would be much appreciated!

1 Like

Ooo! I discovered from here that I can use “url” as a parameter as follows:

data={
"type": "avatar",
"user_id": user_id,
"synchronous": True,
"url":  "url_to_my_image"
}

url = "<my_site>/uploads.json"

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

I finally get a 200!

Now, I know there is a 2nd step I need to do to actually complete this process :thinking:, let me see what I can do…

2 Likes

Yes! I figured out the 2nd step!

url = "<my_site>/users/<username>/preferences/avatar/pick.json"

data={
"upload_id": '<id_from_the_1st_step>',
"type":  'uploaded'
}

response = requests.request("PUT", url, headers=headers, data=data)

Love it! :heart:

1 Like

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