Start a new topic

Accessing data via API with PHP

Hi,


I would like to use the DEAR API to get data into a PHP-based website. I have been trying to get the following to work, but have been unsuccessful. I have tried DEAR Support but they say they don't have any PHP expertise and can't help. Maybe one of you can help me? If i'm on the wrong track, maybe you can provide me with a code sample that does the equivalent of connecting to DEAR and extracting some information.


Here is the code i have been trying:


$account_id = 'account_id_goes_here';
$application_key = 'application_key_goes_here';

$naked_dear_url = 'https://inventory.dearsystems.com/DearApi/Products';

$data = array ('Page' => '1', 'Limit' => '100', 'api-auth-accountid' => $account_id, 'api-auth-applicationkey' => $application_key);
$data = http_build_query($data);

$context_options = array (
        'http' => array (
            'method' => 'GET',
            'header'=> "Content-type: application/json\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
       

$context = stream_context_create($context_options);

$contents = file_get_contents($naked_dear_url, false, $context);
if (!$contents)
{
    echo("file_get_contents: returned FALSE<br>");    // this is where the code ends up - what am i doing wrong?
}
else
{
    $results = json_decode($contents);
    if (!$results)
    {
        echo("json_decode returned FALSE<br>");
    }
    else
    {
        echo("success<br>");
    }
}


Thanks Derek

derek@webascend.com.au




I've got it working using cURL : http://codular.com/curl-with-php


Here's a sample of my code 


$header = array(

    'Content-Type: application/json',

    'api-auth-accountid: '.accountId.'',

    'api-auth-applicationkey: '.applicationKey.'',

);

$dearInventoryUrl = 'https://inventory.dearsystems.com/DearApi/Products?Page=1&Limit=100';


$ch = curl_init();

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

curl_setopt($ch, CURLOPT_URL, $dearInventoryUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

$response = curl_exec($ch);

curl_close($ch);


If you want to do a POST request, the cURL parameters change a bit. You can look it up in the link I posted.

      


1 person likes this

Can't seem to edit. I forgot to put $accountId and $applicationKey instead of accountId and applicationKey, but you get the idea

Login or Signup to post a comment