0

I need to trigger observer whenever I call specific rest api

I've created module/Observer/ObserverClass, module/etc/events.xml and module/etc/webapi-rest/events.xml but I don't know How to trigger it through rest api

how can I do so

0

First initialize webapi

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/hello/name/:name" method="GET">
        <service class="Namespace\Module\Api\HelloInterface" method="name"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Define Interface – etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Namespace\Module\Api\HelloInterface"
                type="Namespace\Module\Model\Hello" />
</config>

Dispatch(initialize) custom observer like below in implementing class

 $textDisplay = new \Magento\Framework\DataObject(array('text' => 'Module'));
    $this->_eventManager->dispatch('namespace_module_display_text', ['mp_text' => $textDisplay]);

After this, call this "namespace_module_display_text" events.xml app/code/Namespace/Module/etc/frontend/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="namespace_module_display_text">
        <observer name="new_event" instance="Namespace\Module\Observer\NewEvent" />
    </event>
</config>

And call observer class

app/code/Namespace/Module/Observer/NewEvent.php

write class definition on above class.

Thanks

  • I have to dispatch the event in Hello class ? – Yomna Mansour Dec 31 '18 at 13:49
0

enter image description here

Please check vendor module: vendor/magento/module-catalog-rule/etc/webapi_rest/events.xml

Also https://mage2.pro/t/topic/137

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.