Shopify Flow

Shopify Flow Deep Dive: Conquering 'Invalid Variable' Errors in Metafield Updates with Admin API Loops

Shopify Flow 'Send Admin API request' action showing an 'invalid variable' error and a suggested 'Foreachitem' variable
Shopify Flow 'Send Admin API request' action showing an 'invalid variable' error and a suggested 'Foreachitem' variable

Shopify Flow Deep Dive: Conquering 'Invalid Variable' Errors in Metafield Updates with Admin API Loops

Hey there, fellow store owners and automation enthusiasts!

As experts at Shopping Cart Mover, we often see merchants leveraging the incredible power of Shopify Flow to automate complex tasks, streamline operations, and boost efficiency. From inventory management to customer engagement, Flow is a game-changer. However, even the most powerful tools can present unique challenges. One common hurdle that recently sparked a lively discussion in the Shopify Community forums is the dreaded "invalid variable" error when attempting to update metafields via the Admin API within a "For each" loop.

This scenario highlights a crucial aspect of advanced Shopify development: precision in variable handling, especially when dealing with iterative processes and API interactions. Let's unpack this mystery and provide clear, actionable solutions to help you build more robust and reliable Shopify Flows.

The Challenge: Tracking Variant Costs with Shopify Flow and Admin API

Our community member, mn175787, was building a highly practical flow: a scheduled daily check designed to detect changes in product variant costs (specifically, those synced from a service like Printful). The goal was two-fold: if a cost changed, the flow would send an internal email alert and then update a last_known_cost metafield directly on the variant. This is a brilliant strategy for maintaining accurate profitability insights and reacting quickly to supplier price fluctuations.

The snag? An error message repeatedly appeared in the "Send Admin API request" action, specifically within the metafieldsSet mutation inputs: "getProductVariantData_item is invalid. Replace this variable." This occurred despite the action being correctly placed inside the "For each" loop. Sound familiar?

This error is a common symptom of a few underlying issues related to how Shopify Flow processes variables, especially within loops and when interacting with the GraphQL Admin API. Let's break down the expert insights from the community and provide a comprehensive guide to resolving these errors.

A close-up of the Shopify Flow 'Send Admin API request' action block, showing a GraphQL mutation input field with a highlighted 'invalid variable' error message, overlaid with a magnifying glass pointing to a Foreachitem variable suggestion.
Debugging 'Invalid Variable' errors in Shopify Flow's Admin API request.

Key Solutions for 'Invalid Variable' Errors in Shopify Flow

1. The Crucial 'Foreachitem' Variable Rule

This was one of the most significant discoveries from the forum thread, emphasized by experts like tim_tairli and Maximus3. When you use a "For each" loop to iterate over a collection of items (like product variants obtained from a "Get product variant data" action), the variables you reference within that loop must include the "Foreachitem" prefix.

  • Incorrect Variable Syntax:
    getProductVariantData_item.id
    getProductVariantData_item.inventoryItem.unitCost.amount
  • Correct Variable Syntax for Loops:
    getProductVariantDataForeachitem.id
    getProductVariantDataForeachitem.inventoryItem.unitCost.amount

Pro Tip: Always use the "Add variable" button within Shopify Flow's action configuration. This built-in helper is designed to suggest the correct variable names, including the `Foreachitem` prefix when applicable, significantly reducing the chances of syntax errors.

2. Data Type Precision: String Casting for `metafieldsSet` Values

As lumine pointed out, the `metafieldsSet` mutation in the Admin API has specific requirements for its `value` argument. Even if you're storing a number (e.g., `number_decimal` or `money`), the `value` passed in the GraphQL variables JSON must be a String.

If your flow is attempting to pass a raw number or a `null` value directly without ensuring it's encapsulated as a string, the API will reject it, leading to an "invalid variable" error.

Example of Corrected Mutation Input:

{
  "metafields": [
    {
      "ownerId": "{{ getProductVariantDataForeachitem.id }}",
      "namespace": "custom",
      "key": "last_known_cost",
      "value": "{{ getProductVariantDataForeachitem.inventoryItem.unitCost.amount | default: '0.00' }}",
      "type": "number_decimal"
    }
  ]
}

Notice the `default: '0.00'` filter. This is crucial for handling cases where `unitCost.amount` might be `null` (see next point). The Liquid output, even for a number, is treated as a string within the double-quotes.

3. Full Global ID (GID) for `ownerId`

The `ownerId` field in the `metafieldsSet` mutation requires the full Global ID (GID) of the resource (e.g., a product variant). This is typically in the format `gid://shopify/ProductVariant/1234567890`, not just the numeric ID.

Fortunately, when you select the `id` variable using the "Add variable" picker in Shopify Flow, it usually provides the correct GID format. Just ensure you're not manually truncating it or using a different variable that only outputs the numeric ID.

4. Handling Null Values Gracefully

External integrations, like Printful in mn175787's case, might occasionally return `null` for certain data points, such as `unitCost.amount`. If a `null` value flows into your GraphQL variables block where a string is expected, it will also trigger an "invalid variable" error.

To prevent this:

  • Use a Conditional Check: Add a condition before your "Send Admin API request" action to check if the `unitCost.amount` variable `is not null`.
  • Apply a Default Filter: As shown in the example above, use the `| default: '0.00'` Liquid filter to provide a fallback value if the original variable is `null` or empty. This ensures a valid string is always passed.

5. Correct Flow Structure and Action Placement

tim_tairli also highlighted the importance of action placement. Ensure your "Send Admin API request" action is genuinely *inside* the "For each" loop, meaning it executes for every item in the loop. If it's mistakenly placed "after last item," the `Foreachitem` context will be lost, leading to invalid variable errors.

Additionally, remember that variables available in "Conditions" might resolve differently or have different scopes than those used in "Actions." Always verify the variable context for each step.

Building Robust Shopify Flows: A Strategic Approach

Mastering Shopify Flow, especially with advanced Admin API integrations, requires attention to detail. By understanding these common pitfalls, you can build more resilient and effective automations. This means more accurate data, better inventory insights, and ultimately, a more profitable business.

If you're looking to start your own e-commerce journey or migrate your existing store to Shopify, remember that powerful automation tools like Flow are a key differentiator. For complex migrations, custom development, or optimizing your e-commerce operations, Shopping Cart Mover is here to help you navigate these intricacies and unlock the full potential of your online store.

Don't let "invalid variable" errors hold you back. With these insights, you're well-equipped to conquer your Shopify Flow challenges and keep your e-commerce engine running smoothly!

Share:

Use cases

Explore use cases

Agencies, store owners, enterprise — find the migration path that fits.

Explore use cases