cUrl to python Conversion Clarifai

Viewed 46

I was trying to access clarifai api , and the following code in cURL is working fine ,

curl -X POST \
  -H "Authorization: Key yyyyyyy" \
  -H "Content-Type: application/json" \
  -d '
  {
    "inputs": [
      {
        "data": {
          "image": {
            "base64": "'"$(base64 /Users/user/Documents/clariFai/test1.jpg)"'"
          }
        }
      }
    ]
  }'\
  https://api.clarifai.com/v2/models/xxxxxxxxxx/outputs

The same i want to use with python ,

what I have tried is

import requests

headers = {
    'Authorization': 'Key yyyyyyy',
    'Content-Type': 'application/json',
}

data = ' { "inputs": [ { "data": { "image": { "base64": "$(base64 /Users/user/Documents/clariFai/test1.jpg)" } } } ] }'

response = requests.post('https://api.clarifai.com/v2/models/xxxxxxxxxx/outputs', headers=headers, data=data)

print(response.content)

But the response I am getting is

b'{"status":{"code":11102,"description":"Invalid request","details":"Malformed or invalid request"}}'

Please help me write the same in correct syntax.

1 Answers

You can try this code to base64 encode the image and send it via requests:

import base64
import requests


headers = {
    "Authorization": "Key yyyyyyy",
    "Content-Type": "application/json",  # <-- maybe not necessary
}

encoded_file = base64.b64encode(open("/Users/user/Documents/clariFai/test1.jpg", "rb").read())
encoded_file = encoded_file.decode("utf-8") # <-- convert it to string


data = {
    "inputs": [
        {
            "data": {
                "image": {
                    "base64": encoded_file  # <-- put base64 encoded file here
                }
            }
        }
    ]
}

response = requests.post(
    "https://api.clarifai.com/v2/models/xxxxxxxxxx/outputs",
    headers=headers,
    json=data,  # <-- use json= parameter
)

print(response.content)

EDIT: Converted the encoded_file to string.

Related