Magento 2 – How to Use Default Methods in REST API

magento-2.1magento2magento2.2restrest api

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.

  • You created the admin user and give all access but still not abel to fetch the product details.

So,here's is the solution and it's working fine in my Magento Version 2.2.4

I created an Admin User.

enter image description here

  • Now i need to fetch the token for that admin user, so i did it using POSTMAN.

Url request type POST

<host>/rest/V1/integration/admin/token?username=aditya&password=aditya@123

which returns token.

"xcph3thmoaiyt0ylm58lf2dn150qlkfr" something like this.


Now using this token we'll fetch the product by SKU for your URL.

URL request type GET

http://127.0.0.1/M224/index.php/rest/V1/products/240-LV09

Payload - Headers

Authorization Bearer xcph3thmoaiyt0ylm58lf2dn150qlkfr

You need pass token in header, that is authntication process which checks the user access in Magento.

In response you'll get Product data


Solution 2

This path of magento catalog API's

vendor/magento/module-catalog/etc/webapi.xml

To fetch products using SKU.

<route url="/V1/products/:sku" method="GET">
        <service class="Magento\Catalog\Api\ProductRepositoryInterface" method="get"/>
        <resources>
            <resource ref="Magento_Catalog::products" />
        </resources>
    </route>

In here, there's resource defined. it means whichever user have access of "Magento_Catalog::products" Only those user can access this API.

<resource ref="Magento_Catalog::products" />

So, if you want to use this API for other users like customer then you can change the resource to self.

Again it will require of token for the same, We don't compromise the security of course

<route url="/V1/products/:sku" method="GET">
            <service class="Magento\Catalog\Api\ProductRepositoryInterface" method="get"/>
            <resources>
                <resource ref="self" />
            </resources>
        </route>

Now, it means we can access it.

  • Using Admin's Token
  • Using Admin User's Token
  • Using Customer's Token.

Yeah,You need to override this file in your module

/vendor/magento/module-catalog/etc/webapi.xml

and then you can access it from customer's token too.

Let me know if you have any query.