Below code is used to add product using a REST API. What I want to achieve is after adding product through the webservice I need to call an observer to perform data insertion to another table.
In the website through admin if I saved the product I am able call the observer but in the REST API it is not triggering.
// Post Data of Products
$sku = uniqid();
$productData = array(
'sku' => $sku,
'name' => 'Simple Product ' . uniqid(),
'visibility' => 4, /*'catalog',*/
'type_id' => 'simple',
'price' => 0.00,
'status' => 1,
'attribute_set_id' => 9,
'weight' => 1,
"extension_attributes"=> [
"stock_item"=> [
"manage_stock"=> 0,
"is_in_stock"=> 1,
"qty"=> "0"
]],
'custom_attributes' => array(
array( 'attribute_code' => 'category_ids', 'value' => ["3"] ),
array( 'attribute_code' => 'description', 'value' => 'Simple Description' ),
array( 'attribute_code' => 'short_description', 'value' => 'Simple Short Description' ),
array( 'attribute_code' => 'chef_name', 'value' => 'Rafsan Chef' ),
array( 'attribute_code' => 'servings', 'value' => '2 people' ),
array( 'attribute_code' => 'cooking_time', 'value' => '20 minutes' ),
array( 'attribute_code' => 'pdf_upload', 'value' => '123.pdf' ),
array( 'attribute_code' => 'steps', 'value' => 'step 1 content###Step 2 content###Step3 Content' ),
)
);
// creating Product using Magento 2 Rest API
$productData = json_encode(array('product' => $productData));
$ch = curl_init("http://127.0.0.1/magento/index.php/rest/V1/products");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
// the Product is Created using the Above Code
// i have created an observer in magento for product save after, that observer is working if it is saved from website admin End. but not working while saving through Rest Api.
// events.xml file created in app/code/[NAMESPACE]/MODULE_NAME/etc/adminhtml/events.xml
<event name="catalog_product_save_after">
<observer name="cus_recipe_saveafter" instance="FreshboxRecipesObserverProductsaveafter" />
</event>
2
Answers
You created events.xml file inside app/code/[NAMESPACE]/MODULE_NAME/etc/adminhtml/ folder, So that is work only from admin area.
To work also from front area using a REST API than you can put events.xml file inside app/code/[NAMESPACE]/MODULE_NAME/etc/ folder instead of app/code/[NAMESPACE]/MODULE_NAME/etc/adminhtml/ folder.
This is the list of events you can hear add product using rest api
This just on add product, not update qty
sales_quote_add_item