JamesHH
JamesHH

Reputation: 51

How do I add a metafield to a Shopify Collection using python API?

I am using the shopify Python API. There is only a short tutorial at

http://wiki.shopify.com/Using_the_shopify_python_api

and it doesn't include anything about metafields. I am not sure how I am meant to translate the shopify API into commands for the Python API. Specifically I would like to know how to add metafields to Shopify resources, for example to a Custom Collection.

Thanks!

Upvotes: 5

Views: 3705

Answers (3)

pa1983
pa1983

Reputation: 274

Rather late to the game, but thought I'd update my findings after this came up in my own research of this problem.

I had a lot of trouble getting this to work and eventually got to this. The key was using the Product.add_metafield function and sending a Shopify.Metafield entry with a 'type' selected from the current version of metafields type list (older answers refer to invalid types). see https://shopify.dev/apps/metafields/types.

    shop_url = f"https://{API_KEY}:{ADMIN_KEY}@{STORE_NAME}.myshopify.com/admin"
    shopify.ShopifyResource.set_site(shop_url)
    prod = shop.Product.find('7279680848024')  # product id
    prod.add_metafield(shopify.Metafield({'type': 'number_integer', 'key':'whs_stock', 'namespace': 'inventory', 'value': 99}))

It's worth noting that if you send the same metafield namespace and key using this method it updates the current metafield instance (retaining the same metafield ID) so you don't need to worry about checking the current value, or whether it exists, before sending new metafield data.

Upvotes: 0

Dylan Smith
Dylan Smith

Reputation: 1522

Metafields have two prefix options, resource and resource_id, otherwise they are like other resource.

So the create Metafield create action in the API documentation can be performed as follows.

metafield = Metafield({'value_type': 'integer', 'namespace': 'inventory', 'value': 25, 'key': 'warehouse', 'resource': 'products', 'resource_id': 632910392})
metafield.save()

There is also an add_metafield method on resources that can take metafields to simplify the above to the following.

product = Product.find(632910392)
metafield = Metafield({'value_type': 'integer', 'namespace': 'inventory', 'value': 25, 'key': 'warehouse'})
product.add_metafield(metafield)

Upvotes: 6

jornak
jornak

Reputation: 478

There is API documentation here in regards to using metafields in the Shopify API.

Upvotes: -1

Related Questions