# Shopify Variant Metafields CSV Validator & Planner (`ministrant_ram/shopify-variant-metafields-planner`) Actor

Validate Shopify variant metafields CSV files before import. Detect row errors and duplicates, then generate metafieldsSet GraphQL batches and JSON diagnostics for AI agents. Supports the custom namespace. No Shopify connection, credentials or writes.

- **URL**: https://apify.com/ministrant_ram/shopify-variant-metafields-planner.md
- **Developed by:** [PlainByte Tools](https://apify.com/ministrant_ram) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / validation report

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Shopify Variant Metafields CSV Validator & Planner

[Shopify's native product CSV does not support variant metafields](https://help.shopify.com/en/manual/products/import-export/using-csv). This Actor validates a CSV of variant metafield values and prepares `metafieldsSet` GraphQL request batches, with explicit column mappings and diagnostics that identify the source row and column. It is designed for agencies, developers and AI agents that already have variant IDs or an exact SKU-to-variant mapping.

**This Actor prepares a plan. It does not connect to Shopify or change a store.** A `ready` result means the checks described below passed. The caller still needs the correct shop, authorization, live variant IDs and matching metafield definitions before executing the requests separately.

### Pricing

**USD 1 per completed validation report, plus USD 0.00005 per Actor start** at the supported memory settings. One run produces one report, regardless of the number of variants, operations or batches within the limits below.

The report price applies to all three outcomes: **`ready`, `blocked` and `no_changes`**. You are paying for validation and planning, including a report that identifies errors or finds nothing to change. The price does not include executing an import in Shopify.

The minimum allowed **maximum cost per run is USD 1.01**. This is a spending limit, not the price: one start and one report total USD 1.00005 in event charges. Platform usage is included in the event pricing. A started run can incur the start event even if it does not produce a report.

#### Preview without running

[Compare three sample reports](https://github.com/plainbyte-tools/shopify-variant-metafields-examples/blob/main/integrations/n8n/sample_responses.json) from fictional data: `ready` shows proposed GraphQL batches, `blocked` shows row-level errors, and `no_changes` shows a report with nothing to apply. Viewing the examples starts no Actor run and costs nothing.

If you use n8n, see the [four-node integration guide](https://github.com/plainbyte-tools/shopify-variant-metafields-examples/tree/main/integrations/n8n). Check the current pricing before running your own CSV. The Actor does not connect to or modify Shopify.

### For AI agents and automation

Choose this tool for an offline validation step before a separately authorized Shopify import: for example, checking supplier CSV values, identifying duplicate destinations, or preparing typed GraphQL requests. It supports the **`custom` namespace** and the six metafield types listed below. It does not fetch variant IDs, resolve SKUs from a live store, read current values or verify live metafield definitions.

The minimum input is **`csv_text` plus `fields`**, which maps each selected CSV column to a namespace, key and type. The default identifier column is `variant_id`, containing canonical ProductVariant GIDs. SKU input additionally requires an explicit `variant_map_csv`; see the input contract. No Shopify token is required or accepted as an input setting.

| Report status | Meaning | Request output |
|---|---|---|
| `ready` | Validation passed and at least one change was planned. | `REQUESTS` contains JSONL; batches are also included in the report. |
| `blocked` | One or more validation errors were found. | No request batches and no `REQUESTS` export. |
| `no_changes` | Validation passed, with no nonblank changes to plan. | No request batches and no `REQUESTS` export. |

An Apify run marked **Succeeded** can contain a `blocked` report: the validation completed successfully, but the input did not pass. The report's `status`, `summary.error_count`, `issues` and `limitations` determine the planning outcome. A `ready` report is not authorization to write to Shopify; applying its requests requires the shop owner's authorization and a separate executor with the appropriate Shopify access. All three report outcomes use the pricing above, including the USD 1.01 minimum run budget.

The same JSON input works through the Apify API. For an MCP-capable client, an [Actor-specific Apify MCP connection](https://mcp.apify.com?tools=ministrant_ram/shopify-variant-metafields-planner) can expose this tool. The client must be configured to connect to Apify, and its user must complete the required authentication and authorize tool use. Publishing the Actor does not automatically connect it to every AI assistant.

### Connect from n8n or an API client

For agencies processing repeated supplier or catalog files, use this Actor as a validation step in an existing workflow. Send one complete file per run, within the documented limits; do not start one run for each CSV row. Keep the same explicit field mappings for files that follow the same agreed format.

#### One HTTP request, one report

Save the JSON example in **How to use it** as `input.json`, replace its fictional data, and configure your own Apify token in the `APIFY_TOKEN` environment variable. The command below starts a billable run using the caller's account and returns a JSON array containing the report. Check the current price and authorize the run before executing it.

```sh
curl --silent --show-error --fail-with-body --retry 0 --max-time 90 \
  --request POST \
  'https://api.apify.com/v2/actors/ministrant_ram~shopify-variant-metafields-planner/run-sync-get-dataset-items?maxTotalChargeUsd=1.01&memory=256&timeout=60&restartOnError=false&format=json' \
  --header "Authorization: Bearer ${APIFY_TOKEN:?Set APIFY_TOKEN in your environment}" \
  --header 'Content-Type: application/json' \
  --data-binary @input.json
```

The USD 1.01 cap applies to this run. Each new run can produce another charge, including reports with errors or no changes. No token belongs in `input.json` or a public workflow export. Read the returned report's `status`; an HTTP success response alone does not mean the input passed validation.

If the connection breaks, check the existing run in Apify Console before repeating the request. A timeout does not prove that no run started or no charge occurred. For production recovery, use the [asynchronous run API](https://docs.apify.com/api/v2/act-runs-post), retain the returned run ID, and retrieve that run's results.

#### Build the validation step in n8n

Use an existing n8n instance with a manual trigger, one input item containing the Actor's JSON, an **HTTP Request** node, and a final step that inspects the report. No AI model or community node is required for this recipe.

| HTTP Request setting | Value |
|---|---|
| Method | `POST` |
| URL | The API URL in the command above, including its query parameters |
| Authentication | Generic Credential Type → Header Auth |
| Credential header | `Authorization`, with value `Bearer YOUR_APIFY_TOKEN` stored in the credential |
| Body | JSON containing `csv_text`, `fields` and the chosen input options |
| Response | JSON; enable **Include Response Headers and Status** |
| HTTP timeout | `90000` milliseconds |
| Retry on fail | Off |

With the full response enabled, the dataset array is in `body`. Require exactly one report and inspect `body[0].status`. A `ready` report can proceed to request review; `blocked` returns diagnostics for correction; `no_changes` has nothing to apply. Do not connect an unconditional Shopify write after the HTTP node. Store access and approval belong in a separately authorized step.

These are integration instructions based on the documented API. A sample workflow configuration and its report-handling JavaScript have been checked locally with fictional `ready`, `blocked` and `no_changes` responses. **A live n8n import and end-to-end run have not been verified.** Your n8n hosting or subscription is separate from the Actor price. Reading the instructions does not execute anything.

[Apify synchronous dataset endpoint](https://docs.apify.com/api/v2/actor-run-sync-get-dataset-items-post) · [n8n HTTP Request documentation](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.httprequest/)

### How to use it

1. Open the Actor's **Input** form in Apify Console. Paste the CSV text and define one mapping for each value column, or switch to JSON and use the example below.
2. Choose the identifier mode and write policy. Keep `create_only` unless you have deliberately chosen another policy. For updates with digest checks, obtain the real current digests from Shopify first.
3. Set a run budget of at least USD 1.01 and start the Actor. Read the report in the default dataset or the `REPORT` storage record.
4. If the report is `ready`, review the generated bodies in `REQUESTS` or `batches[*].request` before passing them to a separately authorized Shopify executor. If it is `blocked`, correct the reported input errors before running again; another completed report is another billable report.

The example uses a **fictional variant ID**. Replace it with an ID from your authorized shop for practical use. Running an example uses the same pricing as any other run. Do not supply Shopify credentials or access tokens to this Actor.

```json
{
  "csv_text": "variant_id,description\ngid://shopify/ProductVariant/1001,Machine washable\n",
  "fields": [
    {
      "column": "description",
      "namespace": "custom",
      "key": "care_instructions",
      "type": "multi_line_text_field"
    }
  ],
  "identifier_mode": "variant_id",
  "identifier_column": "variant_id",
  "write_policy": "create_only",
  "delimiter": ","
}
```

#### Example result: one planned change

This **report excerpt was generated locally from the exact input above**. Metadata, some summary counters and batch bookkeeping fields are omitted; the full report remains the output contract. The included `request` is the complete generated GraphQL body. No request was sent to Shopify.

```json
{
  "status": "ready",
  "remote_requests": 0,
  "definition_constraints_verified": false,
  "summary": {
    "rows_read": 1,
    "planned_operations": 1,
    "batch_count": 1,
    "error_count": 0
  },
  "issues": [],
  "batches": [
    {
      "request": {
        "query": "mutation VariantMetafieldsPlan($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { metafields { id namespace key value compareDigest } userErrors { field message code } } }",
        "variables": {
          "metafields": [
            {
              "ownerId": "gid://shopify/ProductVariant/1001",
              "namespace": "custom",
              "key": "care_instructions",
              "type": "multi_line_text_field",
              "value": "Machine washable",
              "compareDigest": null
            }
          ]
        }
      }
    }
  ]
}
```

#### Example result: an invalid identifier blocks the plan

Keep the mappings and options from the input above, but replace `csv_text` with this CSV, which contains a numeric ID instead of a canonical ProductVariant GID:

```csv
variant_id,description
1001,Machine washable
```

The corresponding **locally generated report excerpt** is below. Unshown metadata and summary counters are omitted. The issue identifies the CSV's second line, and the complete `batches` array is empty.

```json
{
  "status": "blocked",
  "summary": {
    "planned_operations": 0,
    "batch_count": 0,
    "error_count": 1
  },
  "issues": [
    {
      "severity": "error",
      "code": "VARIANT_GID",
      "message": "Identifier does not resolve to one canonical ProductVariant GID.",
      "row": 2,
      "column": "variant_id"
    }
  ],
  "batches": []
}
```

### Input contract

`csv_text` contains the CSV, including its header. `fields` contains 1–20 mappings; each needs `column`, `namespace`, `key` and `type`. Each selected source column maps to one metafield. Only namespace `custom` is supported. Keys must contain 2–64 ASCII letters, digits, hyphens or underscores. The optional `digest_column` is required for every mapping when using `compare_digest`.

`identifier_mode` defaults to `variant_id`, `identifier_column` to `variant_id`, `write_policy` to `create_only`, and `delimiter` to a comma. The delimiter can also be a semicolon or a tab (`"\t"` in JSON). Unknown input settings are rejected.

For SKU input, set `identifier_mode` to `sku`, set `identifier_column` to the column containing SKUs, and supply `variant_map_csv` with exactly `sku,variant_id` columns. Both CSV inputs use the selected delimiter. Duplicate map SKUs block the job, even if they repeat the same ID. Multiple SKUs mapping to the same variant cannot produce duplicate changes to that variant's same metafield.

Variant identifiers must be canonical `gid://shopify/ProductVariant/<positive integer>` strings, with at most 40 digits. Product IDs, numerical IDs without the GID prefix, exponent notation and whitespace-padded identifiers are rejected. Matching is literal and case-sensitive; titles and approximate SKU matches are not used.

### Write policies

| Policy | Generated `compareDigest` | Meaning when the caller executes it |
|---|---|---|
| `create_only` — default | JSON `null` | Create only if the metafield is absent. |
| `compare_digest` | Exact supplied string | Change only if Shopify's current digest matches. Each mapping needs `digest_column`. |
| `overwrite` | Property omitted | Unconditional update/create; the report includes a warning. |

The planner does not calculate digests or convert a missing update digest to `null`. Missing or empty update digests block the entire job.

Each request contains up to 25 metafields. **A plan containing multiple requests is not one atomic transaction:** later requests can fail after earlier ones succeed. Your executor must inspect GraphQL `errors` and `metafieldsSet.userErrors`, respect rate limits and track completed batches. This Actor includes neither a Shopify executor nor an automatic retry loop.

### Supported values and validation

| Type | Validation and handling |
|---|---|
| `single_line_text_field` | Preserve exact text; reject line breaks. |
| `multi_line_text_field` | Preserve exact text, including CSV-quoted newlines. |
| `number_integer` | Canonical decimal integer, from −9,007,199,254,740,991 through 9,007,199,254,740,991; no spaces, plus sign, separators or leading zeros. |
| `number_decimal` | Decimal point, at most nine fractional digits, no exponent or separators; absolute value at most 9999999999999.999999999. Exact decimal arithmetic, without rounding. |
| `boolean` | Literal `true` or `false`, stored as a string. |
| `date` | Real calendar date in `YYYY-MM-DD` format. |

Empty cells are skipped; whitespace-only text is preserved. There is no trimming, locale guessing or automatic type change. A decimal comma or `TRUE` produces an error. Unmapped columns produce a warning. Deletions and list, reference, rich-text and JSON metafields are unsupported.

**Any validation error suppresses every request batch**, including changes from otherwise valid rows. Diagnostics include malformed CSV, missing columns, unsupported values, duplicate destinations and size violations.

### Limits

| Item | Limit |
|---|---|
| Each CSV | 2 MiB of UTF-8 text; 10,000 nonblank data rows |
| Columns | 100; names of 1–128 printable characters |
| Source-column mappings | 20 distinct mappings |
| Nonblank operations | 20,000 |
| Each value | 65,536 UTF-8 bytes |
| Each serialized request | 9,000,000 bytes |
| Complete report | 4,000,000 bytes, measured with ASCII-escaped JSON to allow for storage serialization |
| Displayed diagnostics | 500; total counts and `issues_truncated` indicate omitted diagnostics |

Split inputs that exceed these limits. Blank physical rows are skipped. Diagnostic row numbers refer to the starting physical CSV line, so a quoted multiline cell can span several lines.

Shop-specific metafield definitions can impose additional restrictions. `definition_constraints_verified` is always `false`. The Actor does not check store ownership, permissions, whether IDs exist, current values or digest freshness.

### Outputs and AI integration

Call the Actor through Apify Console or the Apify API with the same JSON input contract. One complete report is stored as one item in the run's default dataset and in the key-value record `REPORT`. The dataset also provides a summary view.

A run stopped before delivery, including for an insufficient budget, must not be treated as a completed plan. The report statuses and their request availability are described in **For AI agents and automation** above.

`batches[*].request` is an ordinary GraphQL HTTP body with `query` and `variables`. Each batch's `source_rows` array is parallel to `variables.metafields` and records the originating row and column. `REQUESTS` contains one such HTTP body per line. **This is not a Shopify Bulk Operations upload format.** Supply shop URLs and credentials only to your separate executor.

### Testing and specifications

Version 0.1.0 has passed 40 local checks and functional cloud tests using fictional data: the valid sample produced 17 operations in one batch; the invalid sample reported nine errors and generated no operations. These tests establish the observed planning behavior; they do not demonstrate Shopify accepting an import.

The request format was reviewed against Shopify Admin API **2026-10** documentation. This project is independent of Shopify and Apify.

- [Native product CSV and variant metafields](https://help.shopify.com/en/manual/products/import-export/using-csv)
- [metafieldsSet](https://shopify.dev/docs/api/admin-graphql/2026-10/mutations/metafieldsSet)
- [MetafieldsSetInput](https://shopify.dev/docs/api/admin-graphql/2026-10/input-objects/MetafieldsSetInput)
- [Metafield types](https://shopify.dev/docs/apps/build/metafields/list-of-data-types)
- [Metafield size limits](https://shopify.dev/docs/apps/build/metafields/metafield-limits)

# Actor input Schema

## `csv_text` (type: `string`):

CSV text with a header row, variant identifiers and metafield values. Variant IDs must have the exact form gid://shopify/ProductVariant/123; numeric IDs are not accepted. The planner enforces the 2 MiB UTF-8 byte limit.

## `fields` (type: `array`):

Map 1 to 20 CSV columns to metafields. This version supports only the custom namespace. With compare_digest, every mapping must specify a digest_column containing the current digest for that metafield.

## `identifier_mode` (type: `string`):

Use canonical Shopify ProductVariant GIDs directly, or resolve SKUs from the mapping CSV you provide. No IDs are inferred or fetched.

## `identifier_column` (type: `string`):

Exact source CSV column name containing the chosen identifier. Set this explicitly to sku when your SKU column is named sku.

## `variant_map_csv` (type: `string`):

Required in sku mode. Supply the exact columns sku and variant_id, with canonical gid://shopify/ProductVariant/... identifiers. Limited to 2 MiB of UTF-8 data and 10,000 data rows. No Shopify lookup is performed.

## `write_policy` (type: `string`):

create_only emits compareDigest: null. compare_digest requires a digest_column in every field mapping. overwrite omits the comparison guard and adds a warning to the report. No policy executes a request.

## `delimiter` (type: `string`):

The delimiter used to parse CSV input.

## Actor input object example

```json
{
  "csv_text": "variant_id,color\ngid://shopify/ProductVariant/123,Blue\n",
  "fields": [
    {
      "column": "color",
      "namespace": "custom",
      "key": "color",
      "type": "single_line_text_field"
    }
  ],
  "identifier_mode": "variant_id",
  "identifier_column": "variant_id",
  "write_policy": "create_only",
  "delimiter": ","
}
```

# Actor output Schema

## `overview` (type: `string`):

One complete report per run, displayed through its summary fields.

## `report` (type: `string`):

The full report, including issues, limitations and mutation batches. Check status before using a plan.

## `requests` (type: `string`):

Available only when report.status is ready. Each line is a request object with query and variables. This is a request plan, not an executed import or a Shopify staged bulk-operation file.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "csv_text": `variant_id,color
gid://shopify/ProductVariant/123,Blue`,
    "fields": [
        {
            "column": "color",
            "namespace": "custom",
            "key": "color",
            "type": "single_line_text_field"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ministrant_ram/shopify-variant-metafields-planner").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "csv_text": """variant_id,color
gid://shopify/ProductVariant/123,Blue
""",
    "fields": [{
            "column": "color",
            "namespace": "custom",
            "key": "color",
            "type": "single_line_text_field",
        }],
}

# Run the Actor and wait for it to finish
run = client.actor("ministrant_ram/shopify-variant-metafields-planner").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "csv_text": "variant_id,color\\ngid://shopify/ProductVariant/123,Blue\\n",
  "fields": [
    {
      "column": "color",
      "namespace": "custom",
      "key": "color",
      "type": "single_line_text_field"
    }
  ]
}' |
apify call ministrant_ram/shopify-variant-metafields-planner --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ministrant_ram/shopify-variant-metafields-planner"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/atxpuxMRdYjr6D2NY/builds/g9pDuxFehYLHedDsl/openapi.json
