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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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.

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

with these methods, we can call API in CakePHP.


0 Comments

Leave a Reply

Avatar placeholder

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