Artificial Intelligence Forum
cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Need Python 3 code snippet to call SAP Leonardo ML ReST API prodimgclassifier

Former Member
1,611

Here's my NON-WORKING version using Python library requests.

import requests
import json
import logging

try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

headers = {'APIKey': 'your API Key',
           'Accept': 'application/json',
           'Content-Type': 'multipart/form-data'}

params = {'files' : 'Desert.jpeg'}
data = {'files' : 'Desert.jpg'} #  url encoded
# data = json.dumps(data) # flat
files = {'files' : open('Desert.jpg', 'rb')}

r = requests.post("https://sandbox.api.sap.com/ml/prodimgclassifier/inference_sync",
                  # params=params,
                  # data=data,
                  headers=headers,
                  files=files)
print('\n------------------\n')
print(r.text)

Response is:

"error_description": "This service requires at least 1 file. Please put your file(s) into the `fil
es` field of the POST request",
1 ACCEPTED SOLUTION
Read only

christianmathias_mueller
Product and Topic Expert
Product and Topic Expert
1,008

Hi Auro,

If you get rid of the 'Content-Type':'multipart/form-data' in the header it should work:

import requests
url = "https://sandbox.api.sap.com/ml/prodimgclassifier/inference_sync"
headers = {'APIKey': <your_API_key>, 'Accept': 'application/json'}
files = {'files': open('desert.jpg', 'rb')}
response = requests.post(url, files=files, headers=headers)
print(response.text)

View solution in original post

2 REPLIES 2
Read only

christianmathias_mueller
Product and Topic Expert
Product and Topic Expert
1,009

Hi Auro,

If you get rid of the 'Content-Type':'multipart/form-data' in the header it should work:

import requests
url = "https://sandbox.api.sap.com/ml/prodimgclassifier/inference_sync"
headers = {'APIKey': <your_API_key>, 'Accept': 'application/json'}
files = {'files': open('desert.jpg', 'rb')}
response = requests.post(url, files=files, headers=headers)
print(response.text)
Read only

Former Member
0 Likes
1,008

Works! Thank you, @

Christian Mathias Mueller