Storefront API - How to get metafields objects in Storefront API response?

dharmeshcrawl
New Member
1 0 0

We are trying to get metafields of a single project using storefront API which returns empty metafields array?

 

Does any knows what are causes here?

Reply 1 (1)
JustinMetros
Tourist
6 1 1

You need to make sure that each of your metafields are exposed to the Storefront API. They are not by default. https://shopify.dev/custom-storefronts/products/metafields#:~:text=about%20a%20store.-,Expose%20meta...

If you use an app like Accentuate, which I highly recommend,  there is an option in there to expose to API making this really easy.

Once they are exposed to the API, there's a few ways to get them.

If you only have a few metafields, you can get them with the productByHandle query under metafields:

example productByHandle.gql

query productByHandle($handle: String!) {
  productByHandle(handle: $handle) {
    id
    title
    tags
    metafields(first: 20) {
      edges {
        node {
          key
          value
          valueType
        }
      }
    }
  ... other fields
}

 

You can also get them by key/namespace and assign to a variable.

Another example productByHandle.gql

query productByHandle($handle: String!) {
  productByHandle(handle: $handle) {
    id
    title
    tags
    someVariableYouMakeUp: metafield(
      namespace: "your_metafield_namespace"
      key: "your_metafield_key"
    ) {
       value
    }
  }
}