calling REST cloudsight api in php

550 Views Asked by At

I am trying to use cloudsight API (http://cloudsight.readme.io/v1.0/docs) that requires me to use both POST and GET. I've never used a REST API before but after doing some research found that to POST using PHP would work.
I found the following code in the api documentation but am not sure how to convert this command line curl to PHP. The response is in JSON.

curl -i -X POST \
-H "Authorization: CloudSight [key]" \
-F "image_request[image][email protected]" \
-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]
2

There are 2 best solutions below

2
On

If using the php curl library, you can do this for the 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 also provides a CURLFile class (http://php.net/manual/en/class.curlfile.php) for working with files instead of passing the path, as in the example above.

For the GET, you can just remove these two lines and alter the url:

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

Another option would be to use Guzzle if you use Composer in your project ( http://guzzle.readthedocs.org/en/latest/).

0
On

If you're still interesting by the answer :

$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 );