How to get product metafields through Shopify's Storefront API

Photo by Growtika on Unsplash

How to get product metafields through Shopify's Storefront API

I ran into a problem where I could not get product metafields to return in the Shopify storefront API. This is important, since I plan to use these metafields on the product page of my headless Shopify build. I resolved the issue in a more digestible way than what is on the official Shopify documentation. So here is my simplified approach.

This tutorial is assuming that you already have storefront API access for your Shopify store.

Step 1: Enable storefront access of metafields through Shopify Admin

Go to settings > custom data > products in your Shopify admin. Here you will be able to see your metafields like so:

Click on a metafield you wish to enable in the storefront API, and enable the Storefronts access button near the bottom. Repeat this for any additional metafields you wish to access.

Step 2: Obtain namespace and key of desired metafields

Go to the same page as above: settings > custom data > products . If you look to the image for step 1, you will see the smaller gray text. This text contains your namespace and key.

For example, if the text is product.metafields.my_fields.description , your namespace will be my_fields and your key will be description . You will need these for the API call in the next step.

Step 3: Make the API call to retrieve metafields

Now you can make your API call to the storefront API. Your call to the storefront should like so:

query ProductMetafields{
  product(id: "your product id") {
    title
    metafield(namespace: "my_fields", key: "description") {
      value
    }
  }
}

This API call will now return your desired metafields. Hope this helped!