Magento 2 How to Create Admin Token Rest API Programmatically?

In Magento 2, sometimes we have a requirement to generate admin token using REST API call. The token we generate using the REST API is an access token which is used for synchronization between Magento and another third-party platform. Without generating an access token, we will not be able to communicate with Magento 2.

To generate an access token, we can use the following code snippet where we need to pass the username and password.

<?php
$url = "http://127.0.0.1/magento2/index.php/rest"; // URL of Magento for REST calls
$tokenUrl = $url."/V1/integration/admin/token"; // Append admin token url params
$username = "admin";
$password = "password@456";
 
//Authentication for rest API in magento2 to get access token
$ch = curl_init();
$data = array("username" => $username, "password" => $password);
$dataString = json_encode($data);
 
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$token = curl_exec($ch);
$accessToken = json_decode($token);
echo $accessToken;exit;

Once we get a response, we can see a string which will be an access token as output. This access token can be used with Authentication request header part in API call.

Output:
dfee21cssa1234sasdfs432sw5467d65

Hope this helps you guys!

Leave a Reply