Reputation: 83
I am trying to make a POST request to a Wordpress REST API using python-requests. The POST data contains an image and meta data (like title and description). The upload of the image is successful without any problem, but none of the caption, description,... data is included. What am I missing? Here is my code
header = {'Authorization': 'Basic ' + token.decode('utf-8'),
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
}
media = {
'file': open("img.jpg","rb"),
'title': "title",
'caption': "caption",
'description': "description",
'alt_text': "alt_text"
}
image = requests.post(url + '/media' , headers= header, files= media,timeout=15)
Upvotes: 2
Views: 1542
Reputation: 5301
I think you may have to make two requests, the first to upload the image, and a second to set the caption and description. The following code should work for you (taken largely from [1]):
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
media = {'file': open('img.jpg','rb')}
# first request uploading the image
image = requests.post(url + '/media', headers=headers, files=media)
# get post-id out of the response to the first request
postid =json.loads(image.content.decode('utf-8'))['id']
# set the meta data
post = {'title': 'title',
'caption': 'caption',
'description': 'description',
'alt_text': 'alt_text'
}
# second request to send the meta data
req = requests.post(url + '/media/'+str(postid), headers=headers, json=post)
[1] https://github.com/timsamart/wp_upload_media
Upvotes: 1