2

I need to add product count with my category listing API response. I tried using Magento's default API rest/V1/categories/list with my searchCriteria

I am getting category data below format.

{
    "items": [
        {
            "id": 8379,
            "parent_id": 2,
            "name": "Sanitarije, grijanje, vodoinstalacije, klima (SGK)",
            "is_active": true,
            "position": 1,
            "level": 2,
            "children": "8380,8602,8965,8980",
            "created_at": "2021-09-28 20:28:39",
            "updated_at": "2022-05-19 08:37:01",
            "path": "1/2/8379",
            "available_sort_by": [],
            "include_in_menu": true,
            "custom_attributes": [...]
        }
    ]
}

I need to add product count with each category response data.

1 Answer 1

1

I got the solution. I have to use the extension_attributes to share the custom data in the category API.

-Create an extension_attributes file in the below path Vendor/Module/etc/extension_attributes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
        <extension_attributes for="Magento\Catalog\Api\Data\CategoryInterface">
            <attribute code="category_product_collection_count" type="Vendor\Module\Api\Data\CategoryCustomDataInterface[]" />
        </extension_attributes>
 </config>

Then after crate a Data interface Vendor\Module\Api\Data\CategoryCustomDataInterface

<?php
    /**
     * Copyright ©  All rights reserved.
     * See COPYING.txt for license details.
     */
    declare(strict_types=1);
    
    namespace Vendor\Moduel\Api\Data;
    
    interface CategoryCustomDataInterface
    {
    
        const CODE = 'code';
        const VALUE = 'value';
    
        /**
         * Get id
         * @return string|null
         */
        public function getCode();
    
        /**
         * @param $code
         * @return mixed
         */
        public function setCode($code);
    
        /**
         * Get content
         * @return string|null
         */
        public function getValue();
    
        /**
         * Set value
         * @param string $value
         * @return \Vendor\Module\Api\Data\CategoryCustomDataInterface
         */
        public function setValue($value);
    }

Define the Data interface to its actual implementation in the model

Vendor\Module\Model\Api\Data\CategoryCustomData

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
declare (strict_types = 1);

namespace Wcb\ApiConnect\Model\Api\Data;

use Magento\Framework\Model\AbstractModel;
use Vendor\Module\Api\Data\CategoryCustomDataInterface;

class CategoryCustomData extends AbstractModel implements CategoryCustomDataInterface
{

    /**
     * @inheritDoc
     */
    public function getCode()
    {
        return $this->_get(self::CODE);
    }
    /**
     * @inheritDoc
     */
    public function setCode($code)
    {
        return $this->setData(self::CODE, $code);
    }

    /**
     * @return string|null
     */
    public function getValue()
    {
        return $this->_get(self::VALUE);
    }

    /**
     * @param string $value
     * @return \Vendor\Module\Api\Data\CategoryCustomDataInterface
     */
    public function setValue($value)
    {
        return $this->setData(self::VALUE, $value);
    }
}

-Need to set the dependencies through di.xml and the path will be etc/webapi_rest/di.xml

  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <preference for="Vendor\Module\Api\Data\CategoryCustomDataInterface" type="Vendor\Module\Model\Api\Data\CategoryCustomData"/>
        
   <type name="Magento\Catalog\Model\CategoryRepository">
           <plugin name="category_product_collection_count" type="Vendor\Module\Plugin\CategoryProductCollectionCountAfterGet"/>
    </type>
       

-And finally, we need to Pass our custom data in the extension_attribute code. Vendor/Module/Plugin/CategoryProductCollectionCountAfterGet.php

 <?php
    namespace Vendor\Module\Plugin;
    
    /**
     * Copyright © Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */
    use Magento\Catalog\Api\Data\CategoryInterface;
    use Magento\Catalog\Api\CategoryRepositoryInterface;
    
    class CategoryProductCollectionCountAfterGet
    {
    
        const PRODUCT_COUNT ='product_count';
    
    
        /**
         * @param CategoryExtensionFactory $extensionFactory
         */
        public function __construct(
        ) {
        }
        public function afterGet(
            CategoryRepositoryInterface $subject,
            CategoryInterface $entity
        ) {
    
    
            $data[$entity->getEntityId()] = ['id'=>$entity->getEntityId(),'product_count'=>$entity->getProductCount(),'product_count_inc_child'=>count($entity->getProductCollection())];
            $extensionAttributes = $entity->getExtensionAttributes(); /** get current extension attributes from entity **/
            $extensionAttributes->setData('category_product_collection_count', $data);
    
    
            $entity->setExtensionAttributes($extensionAttributes);
    
            return $entity;
        }
    
    }
  • Output

    "extension_attributes": { "category_product_collection_count": [ { "id": "8379", "product_count": 6, "product_count_inc_child": 617 } ] },

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.