GraphQL query to get one buyable productVariant id

Unsphere
New Member
2 0 0

Hello,

I need to get randomly one buyable productVariant id for my preview feature via GraphQL API so that I can redirect the customer directly to the cart with an auto-added product (/cart/add?id=variant_id), but unfortunately, I am not able to get the correct query. It seems that more than one query parameter will be not accepted. I tried AND or just whitespace without success.

 

query {
  productVariants(first: 1, query: "published_status:published AND available_for_sale:true") {
    edges {
      node {
        id
        availableForSale
      }
    }
  }
}
query {
  products(first: 1, query: "published_status:published available_for_sale:true") {
    edges {
      node {
        variants(first: 1) {
          edges {
            node {
              id
              availableForSale
            }
          }
        }
      }
    }
  }
}

 

In general, I need a query to get a productVariantId where the product is published and variant is buyable ("quantity" > 0 and track "track quantity" equals true or "Continue selling when out of stock" equals true or "track quantity" equals false).

Any idea? Thanks for your help!

 

Best,

Dennis

0 Likes
CalD
Shopify Staff
Shopify Staff
90 8 12

Hey @Unsphere,

You're almost there. The list of supported filter parameters on products and productVariants is here. For products, you can use published_status and inventory_total. For productVariants, you can use published_status and inventory_quantity.

A sample query would look like this:

query {
  products(first: 1, query: "published_status:published AND inventory_total:>1") {
    edges {
      node {
        variants(first: 1) {
          edges {
            node {
              id
              availableForSale
            }
          }
        }
      }
    }
  }
}

Screen Shot 2020-07-28 at 1.31.09 PM.png

CalD | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

0 Likes
Unsphere
New Member
2 0 0

Hi @CalD,

thanks for your reply. I already tried your queries before, but it is not working if "Track quantity" is unchecked or "Continue selling when out of stock" is checked. Would be great to have available_for_sale as query parameter, because It's exactly what I need. Got it from here.

Best,

Dennis

0 Likes