Home > Framework > CakePHP > How to call API in CakePHP

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

class PagesController extends AppController {

    public function getExternalData(){
        $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

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