Magento 2 Rest API have many default methods. I want to use those method and display data.
For that i have create one new user and assigned full admin access.
Trying to get the product information by SKU using default method:
GET /V1/products/:sku which is given here
Now i am running following url:
http://127.0.0.1/M224/index.php/rest/V1/products/240-LV09
When i run this url in browser it
<response>
<message>Consumer is not authorized to access %resources</message>
<parameters>
<resources>Magento_Catalog::products</resources>
</parameters>
</response>
if i use curl code like this:
$apiURL="http://127.0.0.1/M224/rest/V1/integration/admin/token";
//parameters passing with URL
$data = array("username" => "wuser", "password" => "admin@123");
$data_string = json_encode($data);
$ch = curl_init($apiURL);
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);
//decoding generated token and saving it in a variable
$token= json_decode($token);
//decoding generated token and saving it in a variable
$headers = array("Authorization: Bearer ".$token);
//API URL to get all Magento 2 modules
$requestUrl='http://127.0.0.1/M224/index.php/rest/V1/products/240-LV09';
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//decoding result
$result= json_decode($result);
//printing result
echo "<pre>";
print_r($result);
Which works!
How can i access the default methods and show output? Do i need to curl for this?
For standard practice and MobileAPP output is it good to use CURL to get there?
Is it necessary to write entire token code to get response?
using token it takes time to reponse. Is there any better way?
Any help would be apprecaited.
Best Answer
There are two way for this solution -
1) First let's go to the way where you're facing an issue.
I created an Admin User.
Url request type
POST
which returns token.
"xcph3thmoaiyt0ylm58lf2dn150qlkfr"
something like this.URL request type
GET
Payload - Headers
In response you'll get Product data
Solution 2
This path of magento catalog API's
To fetch products using SKU.
In here, there's resource defined. it means whichever user have access of
"Magento_Catalog::products"
Only those user can access this API.So, if you want to use this API for other users like customer then you can change the
resource
toself
.Now, it means we can access it.
Yeah,You need to override this file in your module
and then you can access it from customer's token too.
Let me know if you have any query.