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
  • 【アプリなし】Shopifyブログのタグ絞り込みを50テーマで比較

    Shopify Blog Tag Filtering Without an App: 50 T...

    Tsun ライターチーム

    We tested 50 Shopify themes in a development store. In 42 themes, the blog page had a tag selector that let us filter posts. Compare single and multiple selection, tags...

    Shopify Blog Tag Filtering Without an App: 50 T...

    Tsun ライターチーム

    We tested 50 Shopify themes in a development store. In 42 themes, the blog page had a tag selector that let us filter posts. Compare single and multiple selection, tags...

  • 【アプリなし】Shopifyテーマのカウントダウンタイマーを50件比較

    [No app required] Countdown timers across 50 Sh...

    Tsun ライターチーム

    We reviewed 50 Shopify themes. On all 39 with a timer, we could still add products to the cart and reach checkout after the deadline. See where to find the...

    [No app required] Countdown timers across 50 Sh...

    Tsun ライターチーム

    We reviewed 50 Shopify themes. On all 39 with a timer, we could still add products to the cart and reach checkout after the deadline. See where to find the...

  • Shopifyテーマの予約販売の対応可否を50件比較|41テーマで予約ボタンを確認

    Pre-order support across 50 Shopify themes | Pr...

    Tsunライターチーム

    We reviewed the official help and the theme editor for 50 Shopify themes. We tried the settings on a development store and confirmed pre-order buttons with no app on 41...

    Pre-order support across 50 Shopify themes | Pr...

    Tsunライターチーム

    We reviewed the official help and the theme editor for 50 Shopify themes. We tried the settings on a development store and confirmed pre-order buttons with no app on 41...

  • Shopify Protect: Rule Builderとは?機能・メリット・料金を解説

    What is Shopify Protect: Rule Builder? Features...

    Tsun ライターチーム

    Explore the features, pricing, and considerations for Shopify's fraud prevention app, Shopify Protect: Rule Builder. Learn about custom rules, testing against orders from the past 90 days, the waitlist, Japanese-language...

    What is Shopify Protect: Rule Builder? Features...

    Tsun ライターチーム

    Explore the features, pricing, and considerations for Shopify's fraud prevention app, Shopify Protect: Rule Builder. Learn about custom rules, testing against orders from the past 90 days, the waitlist, Japanese-language...

  • Shopifyアプリ「ChatGPT」とは?機能・料金・日本での利用条件を解説

    What Is the Shopify App “ChatGPT”? Features, Pr...

    Tsun ライターチーム

    An introduction to the features and pricing of OpenAI’s Shopify app “ChatGPT.” It explains product information sync, information management and analytics in Business Hub, ad delivery, Business Agent features, and...

    What Is the Shopify App “ChatGPT”? Features, Pr...

    Tsun ライターチーム

    An introduction to the features and pricing of OpenAI’s Shopify app “ChatGPT.” It explains product information sync, information management and analytics in Business Hub, ad delivery, Business Agent features, and...

  • Shopifyで使える決済方法一覧|手数料・導入サービス・選び方

    [Complete Guide] A Roundup of Payment Methods A...

    Tsunライターチーム

    This article gives a detailed explanation of the many payment methods available on Shopify and their respective payment processing fees and transaction fees. We also introduce handy Shopify apps that...

    [Complete Guide] A Roundup of Payment Methods A...

    Tsunライターチーム

    This article gives a detailed explanation of the many payment methods available on Shopify and their respective payment processing fees and transaction fees. We also introduce handy Shopify apps that...

1 of 6
  • AI仮想顧客の改善ツール「SimGym」を使ったら売上はどうなった?実行から3か月後までの記録

    What Happened to Sales After Using SimGym, an A...

    テキサス・アユミ

    A record of trying SimGym on the miso specialty store ドットミソ, from checking the proposals through carrying out changes to the look-back three months later. It covers how the order...

    What Happened to Sales After Using SimGym, an A...

    テキサス・アユミ

    A record of trying SimGym on the miso specialty store ドットミソ, from checking the proposals through carrying out changes to the look-back three months later. It covers how the order...

  • 【ストアインタビュー後編】やりながら育てる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...

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.