How to Get Admin Token by REST API in Magento 2?
Magento 2 Admin Token REST API, you need to first generate an access token. The access token is used for synchronization with Magento to another third-party platform.
Without an Access token, you can’t communicate with Magento 2 API that requires Admin Token to fetch results.
To create an access token you need to call POST action with Request payload. Your request URL will be rest/V1/integration/admin/token append to your site URL.
You can check at the end of the page for the POSTMAN screenshot to fetch the access token with POSTMAN.
Pass the username and password in the request body of the Magento backend to generate the Access token.
<?php $url = "http://magento246.docker/index.php/rest"; $token_url = $url."/V1/integration/admin/token"; $username = "admin"; $password = "admin123"; //Authentication rest API magento2, For get access token $ch = curl_init(); $data = array("username" => $username, "password" => $password); $data_string = json_encode($data); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL, $token_url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 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;
A response to the above API call will be the access token as a string.
You can use the response token with an API call in the Header with “Bearer <$accessToken>”
Output:
eyJraWQiOiIxIiwiYWxnIjoiSFMyNTYifQ.eyJ1aWQiOjQwOSwidXR5cGlkIjoyLCJpYXQiOjE2OTY1OTczNjUsImV4cCI6MTY5NjYwMDk2NX0.ao8aP83ax_8OQxo4ldJ5UTeeRPZkPdU2T0sKMuxPrEY
You can use the token in a Web API request as below,
Authorization: Bearer <access token>
Where Replace <access token> token with your actual access token.
PostMan Screen to generate Admin Token for Magento 2,