Index and Cache Management using API in Magento 2

Posted on 1 July, 2019

Index and cache are one of the most important parts of Magento 2. After changing the product data, category data, etc., there is a requirement to reindex Magento indexer for displaying your new data. Now when we are managing the Magento store using API, the data in Magento gets updated directly by API. In this situation, if you want to flush the index and cache also by API, then you can do that by the following technical note.

Using this code, only the invalid indexes & caches will get refreshed. It will not flush all the indexes & caches.

Before we create API, we need admin Access Token for accessing Magento. You can directly create your new Access Token from below path in the admin panel: System > Extensions > Integrations

Now follow the below steps:

INDEX MANAGEMENT

Step 1: Create the webapi.xml file in the \app\code\Emipro\Customapi\etc\webapi.xml folder and paste the below code

1
2
3
4
5
6
7
8
9
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
    <route url="/V1/getinvalidindex" method="GET">
        <service class="Emipro\Customapi\Api\Clearindex" method="getinvalidindex"/>
        <resources>
            <resource ref="admin"/>
        </resources>
    </route>
</routes>

Step 2: Create the di.xml file in \app\code\Emipro\Customapietc\di.xml for API Interface file. So, paste the below code

1
2
3
4
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Emipro\Customapi\Api\Clearindex" type="Emipro\Customapi\Model\Getinvalidindexdata" />
</config>

Step 3: Define getinvalidindex() method in interface file. Create Clearindex.php file in the \app\code\Emipro\Customapi\Api\Clearindex.php folder and paste the below code

1
2
3
4
5
6
7
8
9
10
11
<?php
namespace Emipro\Customapi\Api;
interface Clearindex
{
    /**
     * @api
     * @param
     * @return array
     */
    public function getinvalidindex();
}

Step 4: Define getinvalidindex() in model file. Create Gethighlightdata.php file in the \app\code\Emipro\Customapi\Model\Getinvalidindexdata.php folder and paste the below code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
namespace Emipro\Customapi\Model;
use Emipro\Customapi\Api\Clearindex;
class Getinvalidindexdata implements Clearindex
{
    protected $_indexerFactory;
    protected $_indexerCollectionFactory;
    public function __construct(
        \Magento\Indexer\Model\Processor $processor
    ) {
        $this->processor = $processor;
    }
    public function getinvalidindex()
    {
        $ary_response = [];
        $invalidindex = $this->processor->reindexAllInvalid();
        if ($invalidindex) {
            $this->processor->reindexAllInvalid();
        }
        $invalidI = $this->processor->reindexAllInvalid();
        if (!$invalidI) {
            $valid = [
                "code" => "200",
                "message" => "Indexers are Reindex successfully.",
            ];
        } else {
            $valid = [
                "code" => "300",
                "message" => "Still need to Reindex.",
            ];
        }
        $ary_response[] = $valid;
        return $ary_response;
    }
}

NOTE: To test this API, configure appropriate data in Postman.

URL: BASE_URL/rest/V1/getinvalidindex

Method: GET

Headers:
Authorization => Bearer "YOUR ACCESS TOKEN"
Content-Type => application/json

CACHE MANAGEMENT

If you want to clear invalid cache then just replace below code in \app\code\Emipro\Customapi\Model\Getinvalidindexdata.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
namespace Emipro\Customapi\Model;
use Emipro\Customapi\Api\Clearindex;
class Getinvalidindexdata implements Clearindex
{
    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
        \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
    ) {
        $this->_cacheTypeList = $cacheTypeList;
        $this->_cacheFrontendPool = $cacheFrontendPool;
    }
    public function getinvalidindex()
    {
        $ary_response = [];
        $invalidcache = $this->_cacheTypeList->getInvalidated();
        if($invalidcache){
            foreach ($invalidcache as $key => $value) {
                $this->_cacheTypeList->cleanType($key);
            }
            $valid = [
                "code" => "200",
                "message" => "Cache clean successfully",
            ];
        } else{
            $valid = [
                "code" => "300",
                "message" => "No need to clear cache",
            ];
        }
        $ary_response[] = $valid;
        return $ary_response;
    }
}

NOTE: To test this API, configure appropriate data in Postman.

URL: BASE_URL/rest/V1/getinvalidindex

Method: GET

Headers:
Authorization => Bearer "YOUR ACCESS TOKEN"
Content-Type => application/json

The expected cache result will be as follows:

1
2
3
4
5
6
[
    {
        "code": "200",
        "message": "Cache clean successfully."
    }
]

The expected indexer result as below, 

1
2
3
4
5
6
[
    {
        "code": "200",
        "message": "Indexers are Reindex successfully."
    }
]

I hope this Magento technical note helped you to Manage Magento cache and index using API. If you want to learn custom API in brief, then please refer Create Custom API For Magento 2.

If you have any questions or comments, feel free to post in the comment section and do not miss to share this note with your team!


Angel Patel , eCommerce Engineer

Magento Technical Notes

About Emipro

Being an emerging leader in IT market since 2011, Emipro Technologies Pvt. Ltd. has been providing a wide range of business solutions in Odoo & Magento. We are pleased to have a large pool of contented customers with our meticulous work in the domain of ERP & e-Commerce. Our customers are companies of all sizes ranging from startups to large enterprises who realize that they need a professional internet solution to generate revenue streams, establish proper communication channels, to achieve desired goals and streamline business operations. [....] Read More

Our writings seems informative ?

Subscribe for our Magento Technical Notes and get more amazing stuff directly to your inbox!

Post Your Review

X

Your Review has been posted

0 Comment(s)