How do I create a product with a metafield using a single API call?

I want to create a product with a metafield using a single API call.

Here’s what I’m trying:

require 'shopify_api'

ShopifyAPI::Base.site =  "[https://<REDACTED>:<REDACTED>@ubermart.myshopify.com/admin"](https://<REDACTED>:<REDACTED>@ubermart.myshopify.com/admin&quot);

new_product = ShopifyAPI::Product.new
new_product.title = "Burton Custom Freestlye 151"
new_product.product_type = "Snowboard"
new_product.vendor = "Burton"

new_product.variants = [
  {
    "option_1" => "First",
    "price" => 100,
    "sku" => 'test123',
    "metafields" => [
      {
        "key" => "item_size",
        "value" => '125gr',
        "value_type" => "string",
        "namespace" => "global"
      }
    ]
  }
]

new_product.save

new_product.metafields
# => #<ActiveResource::Collection:0x007f8de3bf9820
 @elements=[],
 @original_params={},
 @resource_class=ShopifyAPI::Metafield>

But this doesn’t work.

I know I could do the following:

require 'shopify_api'

ShopifyAPI::Base.site =  "[https://<REDACTED>:<REDACTED>@ubermart.myshopify.com/admin"](https://<REDACTED>:<REDACTED>@ubermart.myshopify.com/admin&quot);

new_product = ShopifyAPI::Product.new
new_product.title = "Burton Custom Freestlye 151"
new_product.product_type = "Snowboard"
new_product.vendor = "Burton"

new_product.variants = [
  {
    "option_1" => "First",
    "price" => 100,
    "sku" => 'test123'
  }
]

new_product.save

new_product.add_metafield(ShopifyAPI::Metafield.new(:namespace => "global", :key => "item_size", :value => "125gr", :value_type => "string"))

new_product.metafields

But this would consume two API calls to create a single product. I need to import ~26000 products so I need to be as efficient as possible with API calls.

What could I try next?

Hi Narek,

It looks like you’re putting the metafield on the variant in that example, and then at the end you’re looking on the product to see if there are any metafields present. Both products and variants can have metafields, but if you put the metafield on the variant, that’s where it will stay.

If you wanted to check for metafields on the variant that you just created, you would do :

new_product.variants.first.metafields

Hi Shayne,

Thanks a lot.

For those who are interested, here’s how to create a product with a product metafield:

require 'shopify_api'

ShopifyAPI::Base.site =  "[https://<REDACTED>:<REDACTED>@ubermart.myshopify.com/admin"](https://<REDACTED>:<REDACTED>@ubermart.myshopify.com/admin&quot);

new_product = ShopifyAPI::Product.new
new_product.title = "Burton Custom Freestlye 151"
new_product.product_type = "Snowboard"
new_product.vendor = "Burton"

new_product.variants = [
  {
    "option_1" => "First",
    "price" => 100,
    "sku" => 'test123'
  }
]

new_product.metafields = [
  {
    "key" => "item_size",
    "value" => '125gr',
    "value_type" => "string",
    "namespace" => "global"
  }
]

new_product.save

new_product.metafields
1 Like