Camilla Gejl
Camilla Gejl

Reputation: 71

Shopify Storefront API: Getting referenced variant with GraphQL

I'm using the Shopify Storefront API and Accentuate to try to get my hands on a specific variant, but it won't work for me.

THE SHORT VERSION: When I select a variant on the website, I get the url: (... url ...)?variant=31696763027492. How do I get my hands on these numbers after the = for the variant in GraphQL? It does not match the ID.

THE LONG VERSION...

In a product variant, I reference to a variant of another product (with Accentuate). What I need to get out is the variant that I am referencing to.

When I pull out the variant that is being referenced to in the product (as metafield, with GraphQL), I get this:

{
"key": "products_in_package",
"value": "pakke-produkt-gavepose:31696763027492"
}

My problem is the numbers after : in the value. I've found that these are the number that come after the URL of the product when selecting the variant on the "actual" Shopify website ((... url ...)?variant=31696763027492), but I can't see how I can use them, since I can't find these numbers on the actual variant through GraphQL.

It does not match the 'id' or anything else I could find on the variant. Neither can I include the numbers if I try to get productByHandle.

So, does anyone have any ideas on how I can I use it to get the actual product variant through GraphQL? Or ideas on what else I can do to connect a specific product variant to another product variant?

Upvotes: 4

Views: 3015

Answers (3)

Xin
Xin

Reputation: 36520

The storefront API and admin API return different format of Id

  • storefront API: "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzQ3NjA3ODY1MDE3MDM="

  • Admin API: "gid://shopify/Product/4760786501703"

But there is a convert way between each other, use function atob

atob("Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzQ3NjA3ODY1MDE3MDM=") will get the Admin API Id

For NodeJS package: https://www.npmjs.com/package/atob

Upvotes: 4

Camilla Gejl
Camilla Gejl

Reputation: 71

The problem is (or was) that those numbers are not what you get when you get the id from the product through GraphQL. You get a much longer id, like "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8zMTY5NDA3MjQxNDI0NA==".

However, I figures out that using the btoa() JavaScript function on the id you mention (gid://shopify/ProductVariant/31646396055604), I got the long id that I get from the product itself. So problem solved!

Upvotes: 2

drip
drip

Reputation: 12943

The variant ID and GraphQL variant ID is closely related.

  • Variant id - 31646396055604
  • GraphQL Variant id - gid://shopify/ProductVariant/31646396055604

The GraphQL ID is the same as the Variant id but you must add the string gid://shopify/ProductVariant/ before it.

So your GraphQL request will become like so:

{
  productVariant(id:"gid://shopify/ProductVariant/31646396055604"){
    title
    product{
      id
    }
  }
}

Upvotes: 2

Related Questions