Magento – Magento 2 Product save event with Rest API

event-observermagento2rest api

We are using rest API for fetching product of Magento 2 website to our software. This is working fine.

We have connected our software and Magento website with website URL and rest API key of Magento user.

Is there any way to call our software add product page when any product gets added to Magento? Is there any event which will work in rest API, like product save after?

We want to add Magento website product to our software at the same time when the new product gets added to Magento.

Thank you.

Best Answer

I think what you're looking for is catalog_product_save_after. This event gets called for every product save action, including new products.

In order to use it you could do the following in your module:

app\code\Vendor\Module\etc\adminhtml\events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="vendor_module_product_save" instance="Vendor\Module\Observer\Productsaveafter" />
    </event>
</config>

Then in Productsaveafter you can implement logic to connect to your own software and perform actions like adding or updating the product.

Example:

app\code\Vendor\Module\Observer\Productsaveafter.php

<?php

namespace Vendor\Module\Observer;

class Productsaveafter implements ObserverInterface{    

    public function execute(\Magento\Framework\Event\Observer $observer) {

        $product = $observer->getProduct();

        // Your logic to do stuff with $product       

    }
}

UPDATE: The Rest API is one-way only. It's not meant to notify you when changes occur. You're supposed to go get the data yourself. Hence the module suggestion that hooks onto an event.

But if you are unable to add code to Magento, you could implement a lightweight API call that occurs often, say every minute, that queries for the most recent product IDs and compares them to your system. Then if it's a new product you can proceed to get the full product details. There will be a slight delay but it'll still be fast.

Note that it's not an approach that I can recommend because it might put a strain on your store's resources.

Related Topic