How to Manage Index and Cache Management Using Magento 2 REST API?

Today, we’re going to teach you how to manage index and cache management using Magento 2 REST API.

This is often required when you want to change data of a product, category, catalog rules, and so on.

In other words, you will need to re-index for updating your new data. And when you manage your Magento 2 store using the REST API, the data in your store is also updated using the REST API.

So, if you use REST API to manage your store and want to update data, then follow the below step-by-step process.

How to Use REST API to Manage Index and Cache Management in Magento 2

Index Management

Step #1

First of all, we will need to create a registration.php file in app/code/MD/CustomApi/ directory and add the following code.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 */
/**
 * Created By : MageDelight Pvt. Ltd.
 */
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'MD_CustomApi',
    __DIR__ 
);

Step #2

After that, we need to create a module.xml file in app/code/MD/CustomApi/etc/ directory and add the following code.

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Created By : MageDelight Pvt. Ltd.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="MD_CustomApi" setup_version="1.0.0" schema_version="1.0.0" />
</config>

Step #3

Next, we will have to create a di.xml file in app/code/MD/CustomApi/etc/ directory and add the following code.

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Created By : MageDelight Pvt. Ltd.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
   <preference for="MD\CustomApi\Api\UpdateIndex" type="MD\CustomApi\Model\GetInvalidIndexer" />
   <preference for="MD\CustomApi\Api\CleanCache" type="MD\CustomApi\Model\GetRemainCache" />
</config>

Step #4

After that, we will need to create a webapi.xml file in app/code/MD/CustomApi/etc/ directory and copy the following code.

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Created By : MageDelight Pvt. Ltd.
 */
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
   <!-- For Index Management -->
   <route url="/V1/getinvalidindex" method="GET">
      <service class="MD\CustomApi\Api\UpdateIndex" method="getinvalidindex" />
      <resources>
         <resource ref="admin" />
      </resources>
   </route>
   <!-- For Cache Management -->
   <route url="/V1/getremaincache" method="GET">
      <service class="MD\CustomApi\Api\CleanCache" method="getremaincache" />
      <resources>
         <resource ref="admin" />
      </resources>
   </route>
</routes>

Step #5

Now, we need to create an interface file UpdateIndex.php in app/code/MD/CustomApi/Api/ directory and copy the following code.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 */
/**
 * Created By : MageDelight Pvt. Ltd.
 */
namespace MD\CustomApi\Api;
interface UpdateIndex
{
    /**
     * @api
     * @param
     * @return array
     */
    public function getinvalidindex();
}

Step #6

Next, we need to create a GetInvalidIndexer.php file in app/code/MD/CustomApi/Model/ directory and copy the following code.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 */
/**
 * Created By : MageDelight Pvt. Ltd.
 */
namespace MD\CustomApi\Model;
use MD\CustomApi\Api\UpdateIndex;
class GetInvalidIndexer implements UpdateIndex
{
    /**
     * @var \Magento\Indexer\Model\Processor
     */
    protected $processor;
    /**
     * @param \Magento\Indexer\Model\Processor $processor
     */
    public function __construct(
        \Magento\Indexer\Model\Processor $processor
    ) {

        $this->processor = $processor;
    }
    public function getinvalidindex()
    {
        $output = [];
        $invalid_index = $this->processor->reindexAllInvalid();
        if ($invalid_index)
        {
            $this->processor->reindexAllInvalid();
        }
        $inv_ind = $this->processor->reindexAllInvalid();
        if (!$inv_ind)
        {
            $response = [
                "code" => "200",
                "message" => "Indexers are re-index successfully.",
            ];
        }
        else
        {
            $response = [
                "code" => "300",
                "message" => "Please re-index agian.",
            ];
        }
        $output[] = $response;
        return $output;
    }
}

Cache Management

Step #7

Now, the next step is to create another interface file CleanCache.php in app/code/MD/CustomApi/Api/ directory and copy the following code.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 */
/**
 * Created By : MageDelight Pvt. Ltd.
 */
namespace MD\CustomApi\Api;
interface CleanCache
{
    /**
     * @api
     * @param
     * @return array
     */
    public function getremaincache();
}

Step #8

Lastly, we need to create a GetRemainCache.php file in app/code/MD/CustomApi/Model/ directory and add the following code.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 */
/**
 * Created By : MageDelight Pvt. Ltd.
 */
namespace MD\CustomApi\Model;
use MD\CustomApi\Api\CleanCache;
class GetRemainCache implements CleanCache
{
    /**
     * @var \Magento\Framework\App\Cache\TypeListInterface
     */
    protected $cacheTypeList;
    /**
     * @param \Magento\Framework\Model\Context               $context
     * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
     */
    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
    ) {
        $this->_cacheTypeList = $cacheTypeList;
    }
    public function getremaincache()
    {
        $remainCache = $this->_cacheTypeList->getInvalidated();
        if ($remainCache)
        {
            foreach ($remainCache as $key => $value)
            {
                $this->_cacheTypeList->cleanType($key);
            }
            $valid = [
                "code" => "200",
                "message" => "Cache clean successfully",
            ];
        }
        else
        {
            $valid = [
                "code" => "300",
                "message" => "Already cleaned cache.",
            ];
        }
        return $valid;
    }
}

And it’s done!

Now, let’s execute the API output.

Here, all you need to do is execute the below-mentioned URL by Postman, clean the cache, and re-index the indexer using the Magento 2 REST API.

Index Management

  • URL: BASE_URL/rest/V1/getinvalidindex
  • Method: GET
  • Headers:
    • Authorization => Bearer “your access token”
    • Content-Type => application/json

Cache Management

  • URL: BASE_URL/rest/V1/getremaincache
  • Method: GET
  • Headers:
    • Authorization => Bearer “your access token”
    • Content-Type => application/json

Final Words…

With this, we have come to the end of this post. We hope that you found this tutorial helpful.

If you have any questions, please ask them in the comments below. And if you need our professional assistance, feel free to contact us at any time.