How to call API in CakePHP

in CakePHP, Framework / No Comments

This post explains how to call API in CakePHP, in earlier we learn about webservices, documentation for webservices and how to create API in Magento. In the previous post we learn about how to create simple CMS application using CakePHP with SEO friendly URLs. Now we will learn about how call that API in CakePHP. For this follow the below steps.

How to call API in CakePHP by Anil Kumar Panigrahi

How to call API in CakePHP by Anil Kumar Panigrahi

Write the below code in your Controller method

<?php
class PagesController extends AppController {

    public function getExternalData(){
        App::uses('HttpSocket','Network/Http');
        App::uses('Xml','Utility');
        $this->layout = null;
        $this->autorender = false;
        $HttpSocket = new HttpSocket();
        $data = array( ... );
        $response = $HttpSocket->get('[External URL]',$data);
        $request = $HttpSocket->request;
        $xmlString = $response['body'];
    }
}
?>

here External URL is replaced with your external URL, depends on your requirement we can choose the method. Above example code to read the data, we can pass the variables and retrieve data.

If you want to post data then use below method.

<?php $response = $HttpSocket->post('[External URL]',$data); ?>

with these methods, we can call API in CakePHP.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>