How to Make a cURL Request in Magento 2 the RIGHT WAY
While integrating third party APIs call, developers often make a cURL request in Magento 2. You can make a REST web API call using cURL request. Magento 2 provides Magento\Framework\HTTP\Client\Curl class to make a cUrl request. However, developers directly make a cURL request using plain PHP cURL command, which is discouraged.
If you scan your code against Magento 2 coding standard it will show you warning like “The use of function curl_init() is discouraged”.
Today we will see the right way of make a cURL request in Magento 2 using inbuild Magento\Framework\HTTP\Client\Curl class.
Make a POST cURL Request
<?php
namespace Codextblog\Demo\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\HTTP\Client\Curl;
class Inventory extends AbstractHelper
{
/**
* @var Curl
*/
protected $curl;
public function __construct(
Context $context,
Curl $curl,
) {
parent::__construct($context);
$this->curl = $curl;
}
public function makeACurlRequest() {
$URL = 'www.example.com';
$username = 'username';
$password = 'password';
$jsonData = '{}'
//set curl options
$this->curl->setOption(CURLOPT_USERPWD, $username . ":" . $password);
$this->curl->setOption(CURLOPT_HEADER, 0);
$this->curl->setOption(CURLOPT_TIMEOUT, 60);
$this->curl->setOption(CURLOPT_RETURNTRANSFER, true);
//set curl header
$this->curl->addHeader("Content-Type", "application/json");
//post request with url and data
$this->curl->post($URL, $jsonData);
//read response
$response = $this->curl->getBody();
return $response;
}
}
Make a GET cURL Request
<?php
namespace Codextblog\Demo\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\HTTP\Client\Curl;
class Inventory extends AbstractHelper
{
/**
* @var Curl
*/
protected $curl;
public function __construct(
Context $context,
Curl $curl,
) {
parent::__construct($context);
$this->curl = $curl;
}
public function makeACurlRequest() {
$URL = 'www.example.com';
$username = 'username';
$password = 'password';
//set curl options
$this->curl->setOption(CURLOPT_USERPWD, $username . ":" . $password);
$this->curl->setOption(CURLOPT_HEADER, 0);
$this->curl->setOption(CURLOPT_TIMEOUT, 60);
$this->curl->setOption(CURLOPT_RETURNTRANSFER, true);
$this->curl->setOption(CURLOPT_CUSTOMREQUEST, 'GET');
//set curl header
$this->curl->addHeader("Content-Type", "application/json");
//get request with url
$this->curl->get($URL);
//read response
$response = $this->curl->getBody();
return $response;
}
}
For more options of cURL request please visit Magento 2 devdocs.
Leave a Comment
(1 Comment)
please also check the below link for a different way
https://devdocs.magento.com/guides/v2.4/get-started/gs-curl.html
There some other option for the set header etc
Useful Magento 2 Articles
Author Info
Chirag
Connect With MeSponsored