Adding Variant Metafields using Admin REST API

Hello!

I’m writing a Ruby script to input products and their variants from Spree into my Shopify store using the Admin REST API. I am able to get metafields onto my products using the API, but not onto my variants. I am following the instructions laid out in the Admin API docs for creating a product variant with metafields, but I’m not seeing them in the console when I go to Settings > Metafields > Variants (though I do see the metafields I assigned to the products under Products) My code for creating the variants is:

spree_variants.each do |spree_variant|
          spree_variant_sku = spree_variant.sku || ""
          variant = ShopifyAPI::Variant.new(session: @session)
          variant.product_id = product_id # from imported product

          variant_option_values = spree_variant.option_values || []
          variant.title = variant_option_values[0]&.name || spree_variant.product_name
          variant.sku = spree_variant.sku || "default-sku" + Time.now
          variant.price = spree_variant.price ||  0

          variant.metafields = [
            {
              "namespace" => "custom",
              "key" => "spree_variant_id",
              "value" => spree_variant.id,
              "type" => "number_integer"
            }
          ]
            variant.option1 = spree_variant.product_name
          variant.save!

I’m not seeing any errors. I’m doing pretty much the exact same thing for products and it’s working, so I have no idea why this isn’t! Any help would be appreciated.

Thanks!

1 Like