I am currently attempting to use Python (3.5) with the Requests library to send a POST request. This POST will send an image file. Here is the sample code:
import requests
url = "https://api/address"
files = {'files': open('image.jpg', 'rb')}
headers = {
'content-type': "multipart/form-data",
'accept': "application/json",
'apikey': "API0KEY0"
}
response = requests.post(url, files=files, headers=headers)
print(response.text)
However when I run the code I receive a 400 error. I managed to reach the API endpoint, but on the response it states that I failed to send any files.
{
"_id": "0000-0000-0000-0000",
"error": "Invalid request",
"error_description": "Service requires an image file.",
"processed_time": "Tue, 07 Nov 2017 15:28:45 GMT",
"request": {
"files": null,
"options": {},
"tenantName": "name",
"texts": []
},
"status": "FAILED",
"status_code": 400,
"tenantName": "name"
}
The "files" field appears null, which seems a bit odd to me. The POST request worked on Postman, where I used the same header parameters and added image to the body with the "form-data" option (See Screenshot).
Is there something I am missing here? Is there a better way to send an image file over POST with python?
Thank you in advance.
EDIT: A similar question was asked here as pointed by another user. However, if you look into it, my current code is similar to what was suggested as the solution and it still didn't work for me.
Use this snippet
import os
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
name_img= os.path.basename(path_img)
files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
with requests.Session() as s:
r = s.post(url,files=files)
print(r.status_code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With