1
votes

I want to update product metafields in bulk using Shopify Rest API.

This code update only single metafield at a time.

{
  "metafield": 
      { 
       "namespace": "custom_fields",
        "key": "aa_percentage",
        "value": "2345",
        "value_type": "string"
        }

}

I have tried this method, Unfortunately not working.

{
  "metafield": 
      { 
       "namespace": "custom_fields",
        "key": "aa_percentage",
        "value": "2345",
        "value_type": "string"
        },
      { 
       "namespace": "custom_fields",
        "key": "cc_percentage",
        "value": "2345",
        "value_type": "string"
        }                           


}
1

1 Answers

0
votes

This method will not work, because it is not available. Nowhere in the Shopify documentation, there is any bulk update operation for API. Moreover, if you have a look at API Documentation for Metafields, you can add, edit and update only one metafield at a time.

{
  "metafield": {
    "id": 721389482,
    "value": "something new",
    "value_type": "string"
  }
}

But this does not mean that you have to wait for each call to issue the next update. You can generate multiple simultaneous update calls. Doing so can be achieved in many ways like pushing in queue with multiple consumer processes or Promises in JavaScript.

Below is the sample code in NodeJS using Shopify API Node.js (Official module).

const Shopify = require('shopify-api-node');

// create a shopify object
const shopify = new Shopify({
    shopName: 'your-shop-name',
    apiKey: 'your-api-key',
    password: 'your-app-password'
});

// define an array with all metafields that need to be updated
const metafieldsData = [{
        namespace: "custom_fields",
        key: "aa_percentage",
        value: "2345",
        value_type: "string"
    },
    {
        namespace: "custom_fields",
        key: "cc_percentage",
        value: "2345",
        value_type: "string"
    }

];

const promises = [];

// push all the requests in an array
metafieldsData.forEach(metafield => {
    promises.push(shopify.metafield
        .create(metafield));
});

// wait for all api calls to finish
Promise.all(promises).then(response => {
    // do whatever with responses
    console.log(response);
});