9

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.

spdasilv
  • 101
  • 1
  • 1
  • 7
  • 2
    Possible duplicate of [Upload Image using POST form data in Python-requests](https://stackoverflow.com/questions/29104107/upload-image-using-post-form-data-in-python-requests) – joppich Nov 07 '17 at 15:56
  • Hello joppich. 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. – spdasilv Nov 07 '17 at 16:20
  • You are providing the wrong Content-type. – Harshith Thota Feb 16 '18 at 03:12

1 Answers1

10

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)
Alex Montoya
  • 4,697
  • 1
  • 30
  • 31