Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending image over POST request with Python Requests

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.

like image 978
spdasilv Avatar asked Nov 07 '17 15:11

spdasilv


1 Answers

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)
like image 148
Alex Montoya Avatar answered Oct 07 '22 01:10

Alex Montoya