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.")