Magento 2 – Save Product Data for Global Scope Using REST API

magento2rest

I am trying to add product using Rest API. Adding product is working fine.

But I am facing issue in assign in the product information only for Default values instead of copying data for store view. When we select store view Use Default Value checkbox must be checked. Only one attribute value must save in database with scope 0 instead of copying same values for each store.

How can I achieve the above scenario using Rest API ? Below is what I have tried so far:

Case 1:

I tried to call API using the below URL, But It replicate the product values for store view.

POST   /rest/V1/products

Case 2:

I tried to call API using the below URL, But It also replicate the product values for store view.

POST   /rest/{store_code}/V1/products

Case 3:

I tried to call API using the below URL

POST   /rest/all/V1/products

using the above website not assigned to product. so I called catalogProductWebsiteLinkRepositoryV1 to assign product in website as below, but it also replicate the product values for store view.

POST   /rest/V1/products/{sku}/websites

Please suggest how can we save product data for global scope only ?

Note: only have one website, one store and one store view in magento installtion.

Best Answer

This is an acknowledge issue of Magento 2. You can check it over here: https://github.com/magento/magento2/issues/8121

The workaround for your case is setStoreId to zero as @obscure commented. You will do it by override ProductRepository or create a composer patch for it.

app/code/Stackoverflow/Catalog/etc/webapi_rest/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="Magento\Catalog\Model\ProductRepository" type="Stackoverflow\Catalog\Model\Catalog\ProductRepository" />
</config>

app/code/Stackoverflow/Catalog/Model/ProductRepository.php

<?php

namespace Stackoverflow\Catalog\Model;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class ProductRepository extends \Magento\Catalog\Model\ProductRepository
{
    /**
     * Merge data from DB and updates from request
     *
     * @param array $productData
     * @param bool  $createNew
     *
     * @return ProductInterface|Product
     * @throws NoSuchEntityException
     */
    protected function initializeProductData(array $productData, $createNew)
    {
        $product = parent::initializeProductData($productData, $createNew);

        // If product is new, we will store all the values on global scope
        if ($createNew) {
            $productId = $product->getId();
            if (!$productId) {
                $product->setStoreId(0);
            }
        }

        return $product;
    }
}

Hope this helps.