вызов API REST cloudight в стеке переполнения

Я пытаюсь использовать API Cloudight (http://cloudsight.readme.io/v1.0/docs) который требует от меня использовать как POST, так и GET. Я никогда не использовал REST API раньше, но после некоторых исследований выяснил, что POST с использованием PHP будет работать.
Я нашел следующий код в документации API, но не уверен, как преобразовать этот curl командной строки в PHP. Ответ в формате JSON.

curl -i -X POST \
-H "Authorization: CloudSight [key]" \
-F "image_request[image]=@Image.jpg" \
-F "image_request[locale]=en-US" \
https://api.cloudsightapi.com/image_requests


curl -i \
-H "Authorization: CloudSight [key]" \
https://api.cloudsightapi.com/image_responses/[token]

0

Решение

Если вы все еще интересны ответом:

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests" );

$postFields = array(
'image_request' => array(
'remote_image_url'  => $url,
'locale' => 'en-US'
)
);

$fields_string = http_build_query($postFields);

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $fields_string );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Authorization: CloudSight [key]', "Content-Type:multipart/form-data" ) );

curl_exec( $ch );
curl_close( $ch );
1

Другие решения

Если вы используете библиотеку php curl, вы можете сделать это для POST:

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests" );

$postFields = array(
'image_request' => array(
'image'  => '@/path/to/image.jpeg',
'locale' => 'en-US'
)
);

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Authorization: CloudSight [key]' ) );

curl_exec( $ch );
curl_close( $ch );

PHP> = 5.5 также предоставляет класс CURLFile (http://php.net/manual/en/class.curlfile.php) для работы с файлами вместо передачи пути, как в примере выше.

Для GET вы можете просто удалить эти две строки и изменить URL:

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );

Другой вариант — использовать Guzzle, если вы используете Composer в своем проекте ( http://guzzle.readthedocs.org/en/latest/).

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector