$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.
//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:-