Sticky Sticky - 2 months ago 44
Python Question

Python POST request error "image format unsupported" using Microsoft Face API

I'm trying to send a binary image file to test the Microsoft Face API. Using POSTMAN works perfectly and I get back a

faceId
as expected. However, I try to transition that to Python code and it's currently giving me this error:

{"error": {"code": "InvalidImage", "message": "Decoding error, image format unsupported."}}


I read this SO post but it doesn't help. Here's my code for sending requests. I'm trying to mimic what POSTMAN is doing such as labeling it with the header
application/octet-stream
but it's not working. Any ideas?

url = "https://api.projectoxford.ai/face/v1.0/detect"

headers = {
'ocp-apim-subscription-key': "<key>",
'content-type': "application/octet-stream",
'cache-control': "no-cache",
}

data = open('IMG_0670.jpg', 'rb')
files = {'IMG_0670.jpg': ('IMG_0670.jpg', data, 'application/octet-stream')}

response = requests.post(url, headers=headers, files=files)

print(response.text)

Answer

So the API endpoint takes a byte array but also requires the input body param as data, not files. Anyway, this code below works for me.

url = "https://api.projectoxford.ai/face/v1.0/detect"

headers = {
  'ocp-apim-subscription-key': "<key>",
  'Content-Type': "application/octet-stream",
  'cache-control': "no-cache",
}

data = open('IMG_0670.jpg', 'rb').read()

response = requests.post(url, headers=headers, data=data)

print(response.text)
Comments