0

I want to get Category list by authorization bearer key by helper function. I have created custom api module and created helper Data.php and created function for getting generated bearer key.

public function getApiToken()
{
$url = "http://127.0.0.1/magento241/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;
}

Then I have called getApiToken function in model file(Productlistreposito ry.php) by below code:

 public function getCatList($storeId)
    {  
      $dat = $this->dataHelper->getApiToken();
      try{
          $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
          $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
          $baseUrl = $storeManager->getStore()->getBaseUrl();
          $mediaUrl =$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'catalog/category/';
          $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
          $connection = $resource->getConnection();
          $tableName = $resource->getTableName('customapi_items'); 
          $sql = "Select * FROM " . $tableName." WHERE store_id = '".$storeId."'";
          $result = $connection->fetchAll($sql);
          if(count($result)>0){
            $categoryFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
            $categories = $categoryFactory->create();   
            $categories->addAttributeToSelect('*');   
            $categories->addAttributeToFilter('level' , 2);
            $categories->addAttributeToSelect('*')
            ->setStore($storeId);
            foreach ($categories as $category) {
              $shopcat[] = array('id' => $category->getId(),
                  'name' => $category->getName(),
                  'image' => $mediaUrl.$category->getThumbnail(),
                  'cat_url' => $category->getUrl()
              );
              $shopoutput = array_slice($shopcat, 4);
            }
          $msg =['status_code'=> 200, 'status' => 'Success'];
          $msg1 = ['meta' =>$msg, 'data'=>$shopoutput];
          $response = $msg1;
          echo json_encode($response);die; 

          }else{
         // $data1 =['store_id'=> $storeId, 'store_name' =>$storeName,'device_id'=>$deviceid ];
          $msg =['status_code'=> 200, 'status' => 'failed', 'error'=>'Device Id Not valide'];
          $msg1 = ['meta' =>$msg, 'data'=>[]];
          $response = $msg1;
          echo  json_encode($response);die; 
         }
         }catch(\Exception $e){
          $response1 = ['status' => 'Failed', 'message' => $e->getMessage()];

         echo  json_encode($response1, $dat);die;           
         ///return $returnArray;
        } 

In Webapi.xml, I have added:

 <!-- Category List Page API -->
    <route url="/V1/getCatList/:storeId" method="GET">
        <service class="Custom\Mageapi\Api\Productlistpage\ProductListingInterface" method="getCatList"/>
         <resources>
            <resource ref="self"/>
        </resources> 
    </route>

But still getting error, when hit api url, Where I am wrong, please suggest. Is anyone have an idea for that?

<response>
<message>The consumer isn't authorized to access %resources.</message>
<parameters>
<resources>self</resources>
</parameters>

1 Answer 1

0

Instead of passing self in the resources node, pass the resource of the section you want to access instead, pass the following;

<resources>
    <resource ref="Magento_Catalog::categories" />
</resources>

Also make sure the admin user you are using has access to the category section on the admin panel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.