@DTPlayer

Почему API возвращает 400?

Был такой код на PHP
<? $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);?>

Переписал начало в 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())

Но python код выдает bad requests, с чем может быть связанно?
  • Вопрос задан
  • 74 просмотра
Решения вопроса 1
SoreMix
@SoreMix Куратор тега Python
yellow
1.
files = {
    'base64_image': base64.b64encode(open('file.png', 'rb').read()).decode()
}


2. Заголовок Contnet-Type можно удалить
3.
r = requests.post('https://api.shutterstock.com/v2/cv/images', headers=headers, json=files)
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Vindicar
@Vindicar
RTFM!
Использование параметра files подразумевает кодирование Multipart-encoded.
Я подозреваю, нужно использовать параметр data вместо files в обращении к .post().
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы