Trigger Rest-API via curl

This snippet shows how to call a REST-API via curl. It also tells you how you can do a Basic-HTTP-Authentification to legitimate the call.

This snippet shows how to call a REST-API via curl. It also tells you how you can do a Basic-HTTP-Authentification to legitimate the call.

// Get it the REST way over Curl
$mCurl = curl_init();
curl_setopt($mCurl, CURLOPT_URL, $sEndpoint);
curl_setopt($mCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($mCurl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($mCurl, CURLOPT_USERPWD, "$sUsername:$sPassword"); // Authentication via http-auth
curl_setopt($mCurl, CURLOPT_RETURNTRANSFER, 1);

$mCurlResponse = curl_exec($mCurl);
if(!$mCurlResponse){
    throw new Exception("Rest call failed! Call-Data:\n" . print_r(curl_getinfo($mCurl), true));
}

// deal with return http-codes:
// 200 (all Codes starting with 2xx): Call and processing where successful.
// 400 (all Codes starting with 4xx): Call fails - request contains failure
// 500 (all Codes starting with 5xx): Server processing failure
$sStatusCode = curl_getinfo($mCurl, CURLINFO_HTTP_CODE);
$sCallUrl = curl_getinfo($mCurl, CURLINFO_EFFECTIVE_URL);

echo $mCurlResponse . "\n";

curl_close($mCurl);

// OK
if($sStatusCode >= 200 && $sStatusCode < 400){
    //make a SimpleXML Object out of response
    libxml_clear_errors(); //clear Error Buffer
    libxml_use_internal_errors(true); //put on error collection
    #$oXml = simplexml_load_file('/var/www/typomage/app/code/local/SHELDON/Tradebyte/ExcampleData/products.xml');
    $oXml = simplexml_load_string($mCurlResponse);
    if(!$oXml){
        $aErrors = libxml_get_errors(); // get xml parsing errors
        throw new Exception("Error on loading response XML!:\n" . print_r($aErrors));
    }
    return  $oXml;
}
// Call fails - request contains failure
elseif($sStatusCode >=400 && $sStatusCode < 500){
    throw new Exception("Call fails - request contains failure! ($sStatusCode)\nCall was: $sCallUrl\n\nRaw-Return:\n$mCurlResponse");
}
// Server processing failure
elseif($sStatusCode >= 500){
    throw new Exception("Server processing failure! ($sStatusCode)\nCall was: $sCallUrl\n\nRaw-Return:\n$mCurlResponse");
}
// Unexpected status
else{
    throw new Exception("Unexpected HTTP-Status-Code! ($sStatusCode)\nCall was: $sCallUrl\n\nRaw-Return:\n$mCurlResponse");
}

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.