Search code examples
phpapimagentomagento2

Magento 2 - How to call some api when adding or updating a product via admin panel


I want to call an api whenever I add a new product to the catalog or update any product, see screenshot.

Is there any possible solution for this?


Solution

  • You can use an observer on the event catalog_product_save_after for this.

    You needs these files for this in your project:

    app/code/Company/Module/registration.php:

    <?php
    declare(strict_types = 1);
    
    use Magento\Framework\Component\ComponentRegistrar;
    
    ComponentRegistrar::register(
        ComponentRegistrar::MODULE,
        'Company_Module',
        __DIR__
    );
    

    app/code/Company/Module/etc/module.xml:

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Company_Module"/>
    </config>
    

    app/code/Company/Module/etc/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="company_module_product_save_after" instance="Company\Module\Observer\Catalog\ProductSaveAfter" />
        </event>
    </config>
    

    app/code/Company/Module/Observer/Catalog/ProductSaveAfter.php:

    <?php
    declare(strict_types = 1);
    
    namespace Company\Module\Observer\Catalog;
    
    use Magento\Framework\Event\Observer;
    use Magento\Framework\Event\ObserverInterface;
    
    class ProductSaveAfter implements ObserverInterface
    {
        /**
         * Execute observer
         *
         * @param Observer $observer
         * @return void
         */
        public function execute(
            Observer $observer
        ): void {
            // Your code logic here, like:
            $product = $observer->getProduct();
            $productData = $product->getData();
        }
    }
    

    After this run bin/magento setup:upgrade from command line to enable the module.