Get image.id or media.id using Graphql API

mandeepsandhu91
Shopify Expert
5 0 2

I am working on an app where a user can assign multiple media items to a variant. This is working good using rest admin api because I was able to fetch the image-id using Rest admin API and saved it in my database as variant-id, image-id pairs. On the storefront side, I added a custom attribute in liquid coding of the theme like this: 
data-image-id="{{ image.id }}" to identify and compare the images with image-ids saved in my database.

Now I want to make use of the new media object that shopify has introduced. I am using graphQl API to fetch the product images. The Graphql API is returning an image id in a URL like format: "gid://shopify/images/10079785100". The problem is, I am unable to compare and somehow link this id to the image-id or media-id on the storefront. 

So my question is:
1. How can I fetch the actual image.id or media-id for a media item using graphQL API?
2. If that is not possible, then how can I add this gid as a custom attribute for image tag in product page image gallery within the theme code? 

Thanks for any help in advance!

Cheers!

Replies 2 (2)

BeamJokerFavor
Explorer
51 3 6

Isn't the image id the last section of the gid?

oscprofessional
Shopify Partner
15846 2371 3073

Hi @mandeepsandhu91,

Correct me if I am wrong. You wanted to save product image id to database right?

I am sharing two GraphQL queries with you.

1. This will give you first 10 products id, title, handle, image id and url. Here you can change the limit upto 200(first: 200) is max.

Query : 

 

query ProductList{
  products(first: 10) {
    nodes {
      id
      title
      handle
      __typename
      images(first: 5) {
        nodes {
          id
          url
        }
      }
    }
  }
}

 

 

2. This will give you specific product detail by its handle or if you want you can fetch the data by product id:- product(id:"gid://shopify/Product/8119795253543").

Query : 

 

query ProductData {
  productByHandle(handle: "ocean-blue-shirt") {
    id
    images(first: 5) {
      nodes {
        id
        url
      }
    }
  }
}

 

 This will give both image id and image url.

 

I hope this might be helpful for you.

 

Thanks...

Get pass your Store Core Web Vital Free Speed Optimization Audit, Chat on WhatsApp | Skype : oscprofessionals-87 | Email: pallavi@oscprofessionals.com | Custom Pricing Wholesale App : Free | Hire us | Guaranteed Site Speed Optimization | Website Free Audit | Shopify Theme Customization | Build Shopify Private App | Shopify SEO | Digital Marketing