I am currently trying to send a POST request to an image recognition API called CloudSight using Python Requests. I have gotten it working with an image URL, but am struggling to get it to send a local image file. My code so far is:
import requests
LOCALE = 'en-US'
LANGUAGE = 'en-US'
URL = 'http://api.cloudsightapi.com/image_responses/'
header = {
'Authorization' : 'CloudSight meSNWQPE7LZ_ybXLMlDflA'
}
imageFile = {'file': ('cigarette.jpg', open('cigarette.jpg', 'rb'), 'image/jpg')}
def postRequest():
print("Here we go again...")
print(imageFile)
postData = {
'image_request[image]': imageFile,
#'image_request[remote_image_url]': 'https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png',
'image_request[locale]': LOCALE,
'image_request[language]': LANGUAGE
}
rPost = requests.post("https://api.cloudsightapi.com/image_requests", headers=header, data=postData)
print(rPost.status_code)
print(rPost.text)
I am aware that generally Requests sends files using the parameter "files" in the POST request itself:
rPost = requests.post("https://api.cloudsightapi.com/image_requests", headers=header, data=postData, files=imageFile)
However, I have tried both ways and each time get the error: {"error":{"image":["at least one of image or remote_image_url must be set"]}
I also know that the variable is definitely getting the image correctly, as if I print the contents of the variable it gives: {'file': ('cigarette.jpg', <_io.BufferedReader name='cigarette.jpg'>, 'image/jpg')
} As I understand it, the API requires it to be sent in the parameter "image_request[image]" (according to their docs: https://cloudsight.readme.io) How do I send the image file to CloudSight correctly?
Did you try calling the file with the expected name?
imageFile = {'image_request[image]': ('cigarette.jpg', open('cigarette.jpg', 'rb'), 'image/jpg')}
rPost = requests.post("https://api.cloudsightapi.com/image_requests", headers=header, data=postData, files=imageFile)