ShopifyのMetafieldsをGraphQL APIで一括更新する Tsun Inc.

Bulk update Shopify metafields with the GraphQL API

小笠原 京平

"RuffRuff 予約販売" supports the reduction of opportunity losses that occur when products are out of stock, new products are not on sale, or are on backorder.
It's incredibly easy to create pre-orders on your Shopify store, allowing you to register an unlimited number of pre-order products and accept unlimited pre-orders. You can also restrict people from ordering pre-order items and regular items at the same time, or send notifications when the item will be back in stock if it is not yet determined.
There are many unique features that are not found in other pre-order sales apps, such as the "Pay Later" feature that allows you to collect payment before the product is shipped.


My name is Ogasawara and I am CTO at Tsun Inc.!
In this blog, we will share information useful for Shopify development.
I would be happy if this would be helpful for Shopify engineers!

This time, the theme is “Bulk updating Shopify metafields using the GraphQL API.”

What are metafields?
Metafields are a mechanism that allows you to define and add information that is different from the information that can be set by default in Shopify.

Source: https://tsun.ec/blogs/articles/43

The article below also introduces recommended Shopify apps for metafields and bulk editing of metafields, so please refer to it.

What are Shopify metafields? Introducing recommended Shopify apps

Motivation

I used to add metafields using a dedicated Shopify app, but bulk updates require a paid plan, so I thought I would try using the GraphQL API this time.

Also, I had done bulk updates using the GraphQL API before, so I had some idea that metafields could also be updated in the same way.

Prerequisites

Target audience

  • People who have used Shopify's GraphQL API to retrieve or update data
  • People who have used Shopify metafields

Environment

  • Operation has been confirmed using Shopify GraphQL API version 2022-07.

What to prepare

  • Access token for the store to update
  • Tools such as Postman are useful

How to do it

This time, as a sample, we will update the metafields of ProductVariant all at once.

ProductVariant has one metafield called retail_price that represents the retail price.

For how to do bulk updates using the GraphQL API, you can follow the official reference.

There are four general steps as follows.

  1. Prepare a JSONL file (created locally)
  2. Upload the above JSONL file (run stagedUploadsCreate)
  3. Bulk update based on uploaded files (execute bulkOperationRunMutation)
  4. Wait for bulk update to complete

Prepare JSONL file

First, prepare a JSONL file for updating. (Please note that this is JSONL, not JSON)

This JSONL file is OK as long as it contains the ID to identify the target to be updated and the value to be updated.

This time, I created a JSONL file (bulk-update-metafields.jsonl) as shown below.

{ "input": { "id": "gid:\/\/shopify\/ProductVariant\/1", "metafields": { "namespace": "global", "key": "retail_price", "type": "number_integer", "value": "1805" } } }
{ "input": { "id": "gid:\/\/shopify\/ProductVariant\/2", "metafields": { "namespace": "global", "key": "retail_price", "type": "number_integer", "value": "6397" } } }
{ "input": { "id": "gid:\/\/shopify\/ProductVariant\/3", "metafields": { "namespace": "global", "key": "retail_price", "type": "number_integer", "value": "5115" } } }
{ "input": { "id": "gid:\/\/shopify\/ProductVariant\/4", "metafields": { "namespace": "global", "key": "retail_price", "type": "number_integer", "value": "7896" } } }
{ "input": { "id": "gid:\/\/shopify\/ProductVariant\/5", "metafields": { "namespace": "global", "key": "retail_price", "type": "number_integer", "value": "1443" } } }

Upload the JSONL file

Execute the following mutation query against the store you want to update.

mutation {
  stagedUploadsCreate(input:{
    resource: BULK_MUTATION_VARIABLES,
    filename: "bulk-update-metafields",
    mimeType: "text/jsonl",
    httpMethod: POST
  }){
    userErrors{
      field,
      message
    },
    stagedTargets{
      url,
      resourceUrl,
      parameters {
        name,
        value
      }
    }
  }
}

If the query is successful, information such as the key required for upload will be returned, so write it down.

Complete the file upload by specifying the information you noted above and the JSONL file and POSTing it to the Shopify server. (At this point, the file is only uploaded to Shopify's server and not updated.)

Bulk update based on uploaded files

By running a query based on the file uploaded to Shopify's server, you tell Shopify to perform the bulk update.

Specifically, execute the following query.

mutation bulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!) {
  bulkOperationRunMutation(mutation: $mutation, stagedUploadPath: $stagedUploadPath) {
    bulkOperation {
      id
      url
      status
    }
    userErrors {
      field
      message
    }
  }
}
{
  "mutation": "mutation call($input: ProductVariantInput!) { productVariantUpdate(input: $input) { productVariant { metafields(first: 10) { edges { node { namespace key type value } } } } userErrors {  message field } } }",
  "stagedUploadPath": "tmp/55523704929/bulk/d1cbc8f2-a3a7-4808-a148-f9024cfb1126/bulk-update-metafields"
}

Wait for bulk update to complete

Depending on the number of updates, it may take some time to complete the update, so please be patient. (If you set up a webhook, you can also receive the webhook when it is completed)

This time, we will run the following query to check if it is completed.

query {
 currentBulkOperation(type: MUTATION) {
    id
    status
    errorCode
    createdAt
    completedAt
    objectCount
    fileSize
    url
    partialDataUrl
 }
}

The update is complete when the status becomes COMPLETED.

Try getting the target ProductVariant and if you can confirm the update, it's OK.

Summary

This time, I tried updating the metafields set on Shopify ProductVariants in bulk using the GraphQL API.

Of course, if you use an app that supports bulk updates of metafields, you can do it without the hassle of sending queries.

However, internally, apps that update in bulk use the bulk update mechanism introduced this time, so I think it would be useful to know how it works.


At Tsun Inc., we also make extensive use of Shopify metafields to build better stores.

If you would like to build a store, please contact Tsun Inc.

👆️目次はShopifyアプリ「RuffRuff 目次作成」を利用

👆️Table of contents by the Shopify app RuffRuff Table of Contents

Back to blog
1 of 6
  • 【ストアインタビュー後編】やりながら育てるShopify。「野菜をMOTTO」の試行錯誤:モンマルシェ株式会社 河野雄士さん

    [Store Interview, Part 2] Building and Growing ...

    テキサス・アユミ

    "Even when e-commerce is the main battlefield, e-commerce isn't the goal." An in-depth look at our interview with Yuji Kono of Mon Marché, whose brand "Yasai wo MOTTO" grew its...

    [Store Interview, Part 2] Building and Growing ...

    テキサス・アユミ

    "Even when e-commerce is the main battlefield, e-commerce isn't the goal." An in-depth look at our interview with Yuji Kono of Mon Marché, whose brand "Yasai wo MOTTO" grew its...

  • 【ストアインタビュー前編】 ECが主戦場でも、ECが目的ではない。「野菜をMOTTO」が貫くEC戦略:モンマルシェ株式会社 河野雄士さん

    [Store Interview, Part 1] Even When E-Commerce ...

    テキサス・アユミ

    "Even when e-commerce is the main battlefield, e-commerce isn't the goal." Part 1 of our interview with Yuji Kono of Mon Marché, whose brand "Yasai wo MOTTO" grew its e-commerce...

    [Store Interview, Part 1] Even When E-Commerce ...

    テキサス・アユミ

    "Even when e-commerce is the main battlefield, e-commerce isn't the goal." Part 1 of our interview with Yuji Kono of Mon Marché, whose brand "Yasai wo MOTTO" grew its e-commerce...

  • 【ストアインタビュー後編】取り返しのつかない失敗さえしなければ、全部学びになる。EC戦略と経営哲学:Beverich株式会社 代表取締役 木下慶さん

    [Store Interview, Part 2] As Long as You Don't ...

    テキサス・アユミ

    Kei Kinoshita, President of Beverich, discusses his strategy for splitting roles between Shopify and Amazon, how he uses the RuffRuff apps, and a management philosophy that turns failure into learning....

    [Store Interview, Part 2] As Long as You Don't ...

    テキサス・アユミ

    Kei Kinoshita, President of Beverich, discusses his strategy for splitting roles between Shopify and Amazon, how he uses the RuffRuff apps, and a management philosophy that turns failure into learning....

1 of 3
  • Our Editorial Process

    For readers new to e-commerce and Shopify, we write our articles with care to explain difficult commerce and marketing terms, along with how everything works from building a store through to selling, as “gently,” “clearly,” and “accurately” as we can.

    Learn more 
  • About the information on this site

    The information published here is based on Tsun Inc.’s own experience and research. While we make every effort to publish information that is as “current” and “accurate” as possible, we cannot fully guarantee its contents. Tsun Inc. accepts no liability whatsoever for any damages arising from this site. If you find an error in the information published here, we would be grateful if you would contact Tsun Inc.