Magento2 REST API – Token Request Error

apimagento2rest

When I am using content type="application/json",I cant passing any parameters and also returns
"message": "Decoding error."

When I am using content type="application/x-www-form-urlencoded",I cant passing any parameters and also returns

"message": "Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded"

Best Answer

Creating and using rest api in magento 2 is very easy but for that you need some startup example.Magento 2 uses token based rest api.First you need to authenticate user and get the token from magento 2.After getting token you have to pass this token to every request you performed.For example to get product details by SKU you need to first authenticate user and get token now pass this token to your header to call web service /V1/products/:sku

Here I have created example for get product by SKU using magento 2 rest api.Here is list of API that supported by magento 2. LIST OF Methods REST API MAGENTO 2

Below Example please follow

Magento 2 REST API Authentication

//Authentication rest API magento2.Please change url accordingly your url
$adminUrl='http://127.0.0.1/magento2/index.php/rest/V1/integration/admin/token';
$ch = curl_init();
$data = array("username" => "wsuser", "password" => "password123");                                                                    
$data_string = json_encode($data);                       
$ch = curl_init($adminUrl); 
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);
$token=  json_decode($token);                                                
Get Product By SKU REST API Magento 2

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

$requestUrl='http://127.0.0.1/magento2/index.php/rest/V1/products/24-MB01';
//Please note 24-MB01 is sku

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

$result = curl_exec($ch);
$result=  json_decode($result);
print_r($result);
Related Topic