D
D
DTPlayer2021-11-08 22:05:13
Python
DTPlayer, 2021-11-08 22:05:13

Why is the API returning 400?

There was a PHP code like this

<? $imageData = file_get_contents("file.png");
$encodedImageData = base64_encode($imageData);

$uploadBody = [
  "base64_image" => $encodedImageData
];
$uploadEncodedBody = json_encode($uploadBody);

$uploadOptions = [
  CURLOPT_URL => "https://api.shutterstock.com/v2/cv/images",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $uploadEncodedBody,
  CURLOPT_USERAGENT => "php/curl",
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer $SHUTTERSTOCK_API_TOKEN",
    "Content-Type: application/json"
  ],
  CURLOPT_RETURNTRANSFER => 1
];

$handle = curl_init();
curl_setopt_array($handle, $uploadOptions);
$uploadResponse = curl_exec($handle);
curl_close($handle);

$uploadDecodedResponse = json_decode($uploadResponse);
print_r($uploadDecodedResponse);
print_r($uploadDecodedResponse->upload_id);

$similarQuery = [
  "asset_id" => $uploadDecodedResponse->upload_id,
];

$similarOptions = [
  CURLOPT_URL => "https://api.shutterstock.com/v2/cv/similar/images?" . http_build_query($similarQuery),
  CURLOPT_USERAGENT => "php/curl",
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer $SHUTTERSTOCK_API_TOKEN"
  ],
  CURLOPT_RETURNTRANSFER => 1
];

$handle = curl_init();
curl_setopt_array($handle, $similarOptions);
$similarResponse = curl_exec($handle);
curl_close($handle);

print_r($similarResponse);?>

Rewrote beginning in python
import base64
import requests
headers = {
    "Authorization": f'Bearer {token}',
    "Content-Type": 'application/json'
}

files = {
    'base64_image': base64.encodebytes(open('file.png', 'rb').read())
}

r = requests.post('https://api.shutterstock.com/v2/cv/images', headers=headers, files=files)
print(r.json())

But the python code gives out bad requests, what could be the reason?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-11-08
@DTPlayer

one.

files = {
    'base64_image': base64.b64encode(open('file.png', 'rb').read()).decode()
}

2. The Contnet-Type header can be removed
3.
r = requests.post('https://api.shutterstock.com/v2/cv/images', headers=headers, json=files)

V
Vindicar, 2021-11-08
@Vindicar

The use of the files parameter implies Multipart-encoded encoding.
I suspect you should use the data parameter instead of files in the .post() call.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question