Magento 2 REST API

Magento 2 API framework allows developers to create new services for communicating with Magento 2 stores.

Here I will use this Token based REST API to get all the customers from a Magento 2 store. So before each API call we should get the token from Magento and we should pass this token in the header of every request.

Also to achive this you need to create a new admin user with necessary access to the system.

<?php
 $magentoURL = "http://127.0.0.1/mage2/";
 $apiURL = $magentoURL."index.php/rest/V1/integration/admin/token";
 $data = array("username" => "APIUSER", "password" => "APIUSERWD");
 $data_string = json_encode($data);

$ch = curl_init($apiURL);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
 $token = curl_exec($ch);

//decoding generated token and saving it in a variable
 $token= json_decode($token);

//******************************************//

//Using above token into header
 $headers = array("Authorization: Bearer ".$token);

//API URL to get all Magento 2 modules
 $requestUrl =$magentoURL.'index.php/rest/V1/customers/search?searchCriteria[sortOrders][0][field]=email&searchCriteria[sortOrders][0][direction]=asc';

$ch = curl_init($requestUrl);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $result = curl_exec($ch);

//decoding result
 $result= json_decode($result);

//printing result
 echo "<pre>";print_r($result);

?>

Leave a Reply

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