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.