XF 2.2 cant upload attachment with api | python


I cant seem to upload attachment in python i have got the attachment key but I'm unsure how to upload the attachments I've tried everything
if someone can provide a python sample for how to do it it would be appreciated.
Belated reply, but perhaps this will be helpful to anyone else who has grappled with this problem. The following sample Python3 code (minimal error checking) should work with the appropriate substitutions for API key, file path, API URL, and user ID number. Assumes the API key is either for the user with userId or is for a super user or otherwise allowed the operations.

This example updates an existing post with a single attachment. With appropriate code changes additional files may be uploaded using the key created for the first uploaded file using subsequent API calls to the "/attachments/" endpoint (if you don't include a "files" entry in "attachments/new-key" you still get a key useful for subsequent uploads via the "/attachments/" endpoint.) The attachments associated with an attachment key can then be associated with a post using either an update to a post (using a POST to "/post/{postId}/" endpoint) or during post creation (using a POST to the "/posts/" endpoint) by including the "attachment_key" data element.

Assumes python3 with both json and requests modules installed.

import json
import requests

userId = 6
postId = 123
filePath = "path/to/file.jpeg"
apiUrl = "https://www.somedomain.org/index.php/api/"
headers = {"XF-Api-Key": "XYZZY", "XF-Api-User": str(userId)}

data = {"context[post_id]": postId, "type": "post"}
files = {"attachment": open(filePath, "rb")}

# Get an attachment key and also upload the first file.
response = requests.post(f"{apiUrl}attachments/new-key/",
                         headers = headers, data = data, files = files)
if response.reason != "OK":
    raise RuntimeError(f"{response.reason} {content['errors'][0]['message']}")
content = json.loads(response.content)
attachKey = content["key"]
print(f"Uploaded file assigned attachment key {attachKey}")
# Now associate the attachment(s) for that key to an existing post.
data = {"attachment_key": attachKey, "silent": 1}
response = requests.post(f"{apiUrl}posts/{postId}/", headers = headers,
                         data = data)
if response.reason != "OK":
    raise RuntimeError(f"{response.reason} {content['errors'][0]['message']}")
print("Post successfully updated with attachment.")
Top Bottom