CakePHP | Calling Web API in CakePhp 3.x

Author - Parminder Kaur
13.02.2017
|
0 Comments
|

Web API requests in CakePhp 3.x and difference from curl in php.

Cakephp provides an easy method to communicate with webservices as compared to core PHP. In core php we make api requests using curl. Below is the sample code :

function testAPI() {
    header("Content-type: application/json");
    $url = "https://sampleurl.com"; //Url to call using curl
    $param = "authtoken="
    token "; //Paramters to be passed to access the Url
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($result, true);
    return $result;
}

In cakephp above method is written as follows:

Use Cake\Http\Client; //add this Path

public
function testAPI() {
    $http = new Client(['headers' => ['Content-Type' => 'application/json']]);
    $response = $http - > post('https://sampleurl.com', ['authtoken' => 'token']);
    $result = $response - > json;
    return $result;
}

As you can see it’s quite compact and precise in Cake.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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