Categories API Key: Get All Category List Through API Key in Magento 2

This article will help you to get all category list through the API key on the frontend. When we develop a mobile application using Magento for online shopping websites then we need this kind of module to load all the categories data. Using these Categories API key extensions of Magento 2 you will be easily able to get the data.

Categories API Key in Magento 2

 

Custom Categories API key Module To Get Data

In this Magento 2 module, we will show you how you can create Magento 2 extension to get the categories data from a Magento online shopping store through REST API.

Therefore, we have to use a tool to get access to the Magento 2 store data.

So first get the category list we have to create a token that will allow you to get access the Magento 2 website data.

Endpoint:

“http://www.wishusucess.com/rest/V1/integration/admin/token”
app/code/Wishuscess/CategoriesList/registration.php

app/code/Wishuscess/CategoriesList/etc/module.xml

app/code/Wishuscess/CategoriesList/etc/di.xml

app/code/Wishuscess/CategoriesList/etc/webapi.xml

app/code/Wishuscess/CategoriesList/Model/CategoryManagement.php

app/code/Wishuscess/CategoriesList/Model/Category/Tree.php

app/code/Wishuscess/CategoriesList/Api/CategoryManagementInterface.php

app/code/Wishuscess/CategoriesList/Data/CategoryTreeInterface.php

 

Step 1 : Register Categories API Key Module

app/code/Wishuscess/CategoriesList/registration.php

<?php
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishuscess_CategoriesList',
__DIR__
);

 

Step: 2

app/code/Wishuscess/CategoriesList/etc/module.xml

<?xml version="1.0"?>
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_CategoriesList" setup_version="1.0.0">
<sequence>
<module name="Magento_Catalog"/>
</sequence>
</module>
</config>

 

Step 3: Define Dependency of Categories API Key

app/code/Wishuscess/CategoriesList/etc/di.xml

<?xml version="1.0" ?>
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\CategoriesList\Api\CategoryManagementInterface" type="Wishusucess\CategoriesList\Model\CategoryManagement"></preference>
</config>

 

Step 4: Create Categories List Web API

Wishuscess_CategoriesList Magento Web API will help you define your route id that can communicate with your Magento shopping website. So here we will get all category data using these APIs.

app/code/Wishuscess/CategoriesList/etc/webapi.xml

<?xml version="1.0"?>
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/wishusucess/categories" method="GET">
<service class="Wishusucess\CategoriesList\Api\CategoryManagementInterface" method="getTree" />
<resources>
<resource ref="Magento_Catalog::categories" />
</resources>
</route>
</routes>

 

Step 5: Create API Category Management

app/code/Wishuscess/CategoriesList/Model/CategoryManagement.php

<?php
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\CategoriesList\Model;
use Wishusucess\CategoriesList\Api\CategoryManagementInterface;
use Wishusucess\CategoriesList\Model\Category\Tree;

class CategoryManagement extends \Magento\Catalog\Model\CategoryManagement
implements CategoryManagementInterface
{
/**
* @var CategoryRepository
*/
protected $categoryRepository;

/**
* @var Tree
*/
protected $categoryTree;

/**
* @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
*/
private $categoriesFactory;

/**
* @param \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository
* @param Tree $categoryTree
* @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoriesFactory
*/
public function __construct(
\Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
Tree $categoryTree,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoriesFactory
) {
$this->categoryRepository = $categoryRepository;
$this->categoryTree = $categoryTree;
$this->categoriesFactory = $categoriesFactory;
}


}

 

Retrieve Category Data in Tree Structure Magento 2

app/code/Wishuscess/CategoriesList/Model/Category/Tree.php

<?php
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\CategoriesList\Model\Category;

/**
* Retrieve category data represented in tree structure
*/
class Tree
{
/**
* @var \Magento\Catalog\Model\ResourceModel\Category\Tree
*/
protected $categoryTree;

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Magento\Catalog\Model\ResourceModel\Category\Collection
*/
protected $categoryCollection;

/**
* @var \Magento\Catalog\Api\Data\CategoryTreeInterfaceFactory
*/
protected $treeFactory;

/**
* @var \Magento\Catalog\Model\Indexer\Category\Flat\State
*/
protected $flatState;

/**
* @param \Magento\Catalog\Model\ResourceModel\Category\Tree $categoryTree
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\ResourceModel\Category\Collection $categoryCollection
* @param \Magento\Catalog\Api\Data\CategoryTreeInterfaceFactory $treeFactory
*/
public function __construct(
\Magento\Catalog\Model\ResourceModel\Category\Tree $categoryTree,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ResourceModel\Category\Collection $categoryCollection,
\Magento\Catalog\Model\Indexer\Category\Flat\State $flatState,
\Magento\Catalog\Api\Data\CategoryTreeInterfaceFactory $treeFactory
) {
$this->categoryTree = $categoryTree;
$this->storeManager = $storeManager;
$this->categoryCollection = $categoryCollection;
$this->treeFactory = $treeFactory;
$this->flatState = $flatState;
}

/**
* @param \Magento\Catalog\Model\Category|null $category
* @return Node|null
*/
public function getRootNode($category = null)
{
if ($category !== null && $category->getId()) {
return $this->getNode($category);
}

$store = $this->storeManager->getStore();
$rootId = $store->getRootCategoryId();

$tree = $this->categoryTree->load(null);
$this->prepareCollection();
$tree->addCollectionData($this->categoryCollection);
$root = $tree->getNodeById($rootId);
return $root;
}

/**
* @param \Magento\Catalog\Model\Category $category
* @return Node
*/
protected function getNode(\Magento\Catalog\Model\Category $category)
{
$nodeId = $category->getId();
$node = $this->categoryTree->loadNode($nodeId);
$node->loadChildren();
$this->prepareCollection();
$this->categoryTree->addCollectionData($this->categoryCollection);
return $node;
}

/**
* @return void
*/
protected function prepareCollection()
{
$storeId = $this->storeManager->getStore()->getId();
$this->categoryCollection->addAttributeToSelect(
'name'
)->addAttributeToSelect(
'is_active'
)->setProductStoreId(
$storeId
)->setLoadProductCount(
true
)->setStoreId(
$storeId
);

if ($this->flatState->isAvailable()) {
$this->categoryCollection->addAttributeToSelect('image');
} else {
$this->categoryCollection->addAttributeToSelect('image', true);
}
}

/**
* @param \Magento\Framework\Data\Tree\Node $node
* @param int $depth
* @param int $currentLevel
* @return \Magento\Catalog\Api\Data\CategoryTreeInterface
*/
public function getTree($node, $depth = null, $currentLevel = 0)
{
/** @var \Magento\Catalog\Api\Data\CategoryTreeInterface[] $children */
$children = $this->getChildren($node, $depth, $currentLevel);
/** @var \Magento\Catalog\Api\Data\CategoryTreeInterface $tree */
$tree = $this->treeFactory->create();
$tree->setId($node->getId())
->setParentId($node->getParentId())
->setName($node->getName())
->setPosition($node->getPosition())
->setLevel($node->getLevel())
->setIsActive($node->getIsActive())
->setProductCount($node->getProductCount())
->setImage($node->getImage())
->setChildrenData($children);
return $tree;
}

/**
* @param \Magento\Framework\Data\Tree\Node $node
* @param int $depth
* @param int $currentLevel
* @return \Magento\Catalog\Api\Data\CategoryTreeInterface[]|[]
*/
protected function getChildren($node, $depth, $currentLevel)
{
if ($node->hasChildren()) {
$children = [];
foreach ($node->getChildren() as $child) {
if ($depth !== null && $depth <= $currentLevel) {
break;
}
$children[] = $this->getTree($child, $depth, $currentLevel + 1);
}
return $children;
}
return [];
}
}

 

Step 7: Retrieve List of Categories

app/code/Wishuscess/CategoriesList/Api/CategoryManagementInterface.php

<?php
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\CategoriesList\Api;

/**
* @api
*/
interface CategoryManagementInterface
{
/**
* Retrieve list of categories
*
* @param int $rootCategoryId
* @param int $depth
* @throws \Magento\Framework\Exception\NoSuchEntityException If ID is not found
* @return \Wishusucess\CategoriesList\Api\Data\CategoryTreeInterface containing Tree objects
*/
public function getTree($rootCategoryId = null, $depth = null);

/**
* Move category
*
* @param int $categoryId
* @param int $parentId
* @param int $afterId
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function move($categoryId, $parentId, $afterId = null);

/**
* Provide the number of category count
*
* @return int
*/
public function getCount();
}

 

Step 8: Category Tree Interface - Categories API Key

app/code/Wishuscess/CategoriesList/Data/CategoryTreeInterface.php

<?php
/**
* Developer:Wishuscess Magento 2x Developer Team
* Module: Wishuscess_CategoriesList
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\CategoriesList\Api\Data;

/**
* @api
*/
interface CategoryTreeInterface
{
/**
* @return int|null
* 
*/
public function getId();

/**
* @param int $id
* @return $this
*/
public function setId($id);

/**
* Get parent category ID
*
* @return int
*/
public function getParentId();

/**
* Set parent category ID
*
* @param int $parentId
* @return $this
*/
public function setParentId($parentId);

/**
* Get category name
*
* @return string
*/
public function getName();

/**
* Set category name
*
* @param string $name
* @return $this
*/
public function setName($name);

/**
* Get category image
*
* @return string
*/
public function getImage();

/**
* Set category image
*
* @param string $name
* @return $this
*/
public function setImage($image);

/**
* Check whether category is active
*
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function getIsActive();

/**
* Set whether category is active
*
* @param bool $isActive
* @return $this
*/
public function setIsActive($isActive);

/**
* Get category position
*
* @return int
*/
public function getPosition();

/**
* Set category position
*
* @param int $position
* @return $this
*/
public function setPosition($position);

/**
* Get category level
*
* @return int
*/
public function getLevel();

/**
* Set category level
*
* @param int $level
* @return $this
*/
public function setLevel($level);

/**
* Get product count
*
* @return int
*/
public function getProductCount();

/**
* Set product count
*
* @param int $productCount
* @return $this
*/
public function setProductCount($productCount);

/**
* @return \Wishusucess\CategoriesList\Api\Data\CategoryTreeInterface[]
*/
public function getChildrenData();

/**
* @param \Wishusucess\CategoriesList\Api\Data\CategoryTreeInterface[] $childrenData
* @return $this
*/
public function setChildrenData(array $childrenData = null);
}

 

Now, Run Following Command:

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy -f

php bin/magento cache:clean

php bin/magento cache:flush

 

Now you have the complete module so using this category API key module you can retrieve the category data from other frontend stores in  ReactJS or NodeJS. All you have to do is just call this API key your Reactjs or Nodejs store and you will get the data.

Hire Magento 2 Expert Developer to Develop Your Store

 

Related Post:

Custom Shipping Text Filed: Show Custom Text Magento 2

 

Recommended Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

SEO Packages: How Much Do SEO Packages Cost in India, SEO Pricing