1

I am new to Magento 2. I need help in the following query.

How to call an external API on page load or on click of a button in Magento 2.2?

Do we need to create an observer for the same or is there a better way to do it. Will appreciate if any links are provided for step by step process.

Pingolin
  • 3,161
  • 6
  • 25
  • 40

1 Answers1

0

First of all, we need to know how to call a basic API. Here is example about GET:

$externalAPI = 'https://your/external/api_url'

$ch = curl_init($externalAPI);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
 
$result = curl_exec($ch);
 
var_dump($result);

From the Magento side, we can use \Magento\Framework\HTTP\Client\Curl class:

$apiUrl = '';
$this->curl->addHeader('Content-Type', 'application/json');
$this->curl->get($apiUrl);
$body = $this->curl->getBody();
$httpCode = $this->curl->getStatus();
//Quick decoding body
$dataResponse = \Zend_Json::decode($body);

How to call an external API on page load or on click of a button in Magento 2.2?

Do we need to create an observer for the same or is there a better way to do it.

It depends on the requirements. When do you need to connect to API? Or just display it on the frontend?

Once you know when(or where?) you need to call the external API. You can choose the Plugin, Observer, or Ajax solution.

Community
  • 1
  • 1
Khoa TruongDinh
  • 913
  • 1
  • 13
  • 26