Magento2 how to get token by rest api?

user3404608 picture user3404608 · Apr 29, 2016 · Viewed 8.4k times · Source
$adminUrl='http://localhost/magento/index.php/rest/V1/integration/admin/token';

$data = array("username" => "myname", "password" => "mypassword");                                                                    
$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);
print_r($token);

I have try above code , but can not get a token , and return an error message ({"message":"Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded"}, anyone know how to do,please help,Thanks.

Answer

Kapil Singhathia picture Kapil Singhathia · Jun 10, 2016
//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); 

Above peace of code will resolve your issue follow the block:-

http://blog.i13websolution.com/magento-2-rest-api-example/