How to properly fetch collections metafields with Storefront API?

alek07
New Member
4 0 0

Hey everyone, I'm trying to fetch all the metafields inside a collections query. This is the query I'm trying to use, but the metafields array always return null.

query getCollections(
  $cursor: String
) {
  collections(first: 250, after: $cursor) {
    edges {
      cursor
      node {
        id
        title
        image {
          url
        }
        metafields(identifiers: [{ key: "show_in_home", namespace: "settings" }]) {
          value
        }
      }
    }
  }
}

but if I query the same metafield like this it works, but I want to fetch all metafields, not just one:

ShowInHome: metafield(namespace: "settings", key: "show_in_home") {
  value
}

What is the difference between both properties and which is the best way to get all metafields?

 

Replies 3 (3)

ankitpateldev
Shopify Partner
15 1 2

Hi @alek07 ,

If you wish to fetch metafields value for specific namespace and key then you use below query. You are using indentifiers that is non-recognise parameter that's why it returns null.

 

Please try below query:
query getCollections(
  $cursor: String
) {
collections(first: 250, after: $cursor) {
  edges {
    cursor
    node {
     id
     title
     image {
      url
    }
    metafields(first:250, keys: ["settings.show_in_home", "custom.related", "custom.sample_text"]) {
     nodes {
       value
       namespace
       key
    }
  }
 }
}
}
}

Best regards,
Ankit Patel | Shopify Expert
alek07
New Member
4 0 0

Hello @ankitpateldev,

 

I tried the query you suggested, but I get an error saying that the indentifiers is a required argument for Metafields field and that first and key are not valid arguments.

ankitpateldev
Shopify Partner
15 1 2

Hi @alek07 ,

I really apologise for that the above query was for the admin API call. And if you are trying with storefront API can you please use below query. It's 100% working and I already tested.

query collections($cursor: String, $identifiers: [HasMetafieldsIdentifier!]!){
      collections(first: 5, , after: $cursor) {
        edges {
          cursor
          node {
            id
            title
            image {
              url
            }
            metafields( identifiers: $identifiers) {
              namespace
              key
              value
            }
          }
        }
      }
    }`,
    {
    variables: {
      "identifiers": [
        {
          "key": "related",
          "namespace": "custom"
        },
        {
          "key": "sample_text",
          "namespace": "custom"
        }
      ],
      "cursor": null
    }
  }

 

Best regards,
Ankit Patel | Shopify Expert