shopify-api-ruby: Error when updating metafields on a product
When I try to do this:
shopify_product = ShopifyAPI::Product.find(123456)
shopify_product.metafields = [{
key: "someKey",
value: "new value,
value_type: "string",
namespace: "MyNamespace"
}]
shopify_product.save
I’m getting this error: :key=>["must be unique within this namespace on this resource"]
This namespace/key already exists on this product, I’m just trying to update its value to “new value”, but this error is preventing it. How do I do this?
#419 could be related.
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 15 (4 by maintainers)
Shopify API should really support this. It takes extreme overhead to update a single entity.
Well, can it become a feature request? 😉
Unfortunately the REST API doesn’t support the action of updating metafields through the Product resource, you’re only able to create new ones. Let me know if there are any more questions! I’ll be closing the issue for now since this isn’t a shopify_api bug.
You can use the Product API to update or create a metafield when you call
PUT /products/PRODUCT_ID.jsonBut after you save a product you don’t get the metafields, so you need to call first
/metafields.json?metafield[owner_id]=PRODUCT_ID&metafield[owner_resource]=productHello guys. my name is Bernardo.
There is a way to update the metafields without so many problems. I hope my example helps you.
To update the metafield through the customer API it is necessary to pass the id of the metafield that will work.
Enter in:
{domain}/admin/customers/{customer_id}/metafieldsSo that all metafields created for the customer are listed. In this list, you can find out which is the id of the metafield that you need to update.Then just run this code snippet that updates the customer data:
I think I could solve it!
First I got the id of the metafield like this:
endpoint = "metafields.json?metafield[owner_id]= (customer_id) &metafield[owner_resource]=customer"Then with help of this reference: https://shopify.dev/api/admin-rest/2021-10/resources/metafield#put-metafields-metafield-id , I could update my customer’s metafield.
endpoint = "customers/" + (customer_id) + "/metafields/" + (metafield_id) + ".json"json = {"metafield":{"id":(metafield_id) ,"value": (metafield_value),"type":"single_line_text_field"}}response = requests.put(url + endpoint,json=json)I hope it helps!