CakePHP | Calling Web API in CakePhp 3.x

|
| By Webner

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.

Leave a Reply

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