0
votes

Set-up

I have created a smart collection in Shopify.

In the admin of the shop I can set the SEO metafields of the collection, however I'd like to do this via the API.


Code

To do so, I use the following code,

payload = {
    'metafields': [
        {
           'namespace': 'global',
           'key': 'title_tag',
           'value': collection_title + ' – Kappersstoelshop.nl',
           'value_type': 'string',
           },
        {
           'namespace': 'global',
           'key': 'description_tag',
           'value': collection_title +' ✅ Gratis bezorgd vanaf €70 ✅  14 dagen bedenktijd ✅  Leasen, gespreid of achteraf betalen',
           'value_type': 'string',},
        ]
    }

r = requests.post(shop_url + '/collections/'+collection_id+'/metafields.json',
                  json=payload,headers=headers)

where collection_title and collection_id are strings.

I have based this code on the method to insert metafields to products, namely,

r = requests.post(shop_url + '/products/'+product_id+'/metafields.json',
                  json=payload,headers=headers)

Issue

The above code yields a <Response [400]> error code, which according to Shopify API response codes means;

The request was not understood by the server, generally due to bad syntax or because the Content-Type header was not correctly set to application/json. This status is also returned when the request provides an invalid code parameter during the OAuth token exchange process.

Now, admittedly Shopify doesn't give any explanation on how to exactly create a metafield of a collection, other than naming collections here as a resource that can have metafields and stating something here about creating metafields for 'shop resources'.


Question

Any idea how to create a metafield for a (smart) collection via the API?

1

1 Answers

0
votes

with your given payload, the API responds with 404 and the following error for me:

{
    "errors": {
        "metafield": "Required parameter missing or invalid"
    }
}

The metafields endpoint doesn't allow to create multiple metafields in a single request. It takes only a single metafield in the body https://shopify.dev/docs/admin-api/rest/reference/metafield?api%5Bversion%5D=2021-04#create-2021-04 . You'll probably need to perform multiple POST requests with a payload like the following:

payload = {
    'metafield':
        {
           'namespace': 'global',
           'key': 'title_tag',
           'value': collection_title + ' – Kappersstoelshop.nl',
           'value_type': 'string',
         }
    }

Another option, if you really need the insertion of the metafields to be atomic, would be to change the value_type to json_string and combine all data in the value.