Custom API integration in magento2

If we would need any API integrations on sometimes to connect with any external platform to send and receive data. Magento has its own integration API for its predefined events such as product, category, etc integrations.
But need to do any external API calls for a particular reason or functionality, we can use PHP CURL method for the same.
It is one of the main PHP methods to sent and receive data from external platforms.

CURL Get Function

$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “GET”,
CURLOPT_HTTPHEADER => array(
“accept: /“,
“accept-language: en-US,en;q=0.8”,
“content-type: application/json”,
“User-Agent: Mozilla/5.0”
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);


CURL Post function

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parms));
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘Content-Type: application/json’,
$authorize
)
);
//execute post
$result = curl_exec($ch);
curl_close($ch);

Both requests should contain URL, header/authorization header and the post function have the post data.

Thank you.

Leave a comment

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