How to Fetch Product Media Gallery Images URLs using GraphQL in Magento 2?

Magento 2 is a popular and powerful e-commerce platform that provides extensive APIs to interact with its database and fetch various types of data. One of the essential aspects of any online store is product images, and in Magento 2, these images are stored in the product media gallery. In this tutorial, we will explore how to fetch product media gallery images URLs using GraphQL in Magento 2.

Before we proceed, make sure you have the following:

  1. A working Magento 2 store with GraphQL enabled.
  2. Familiarity with GraphQL queries and Magento 2 GraphQL schema.

Step 1: Set up GraphQL Endpoint

To begin, ensure that the GraphQL module is installed and enabled in your Magento 2 instance. Once enabled, you can access the GraphQL endpoint via https://your-magento-store/graphql.

Step 2: Understand GraphQL Schema

Before we create the GraphQL query, let's understand the schema to know which fields we can query. In Magento 2, the media gallery is part of the product object and can be accessed using the media_gallery field.

Here's a simplified representation of the schema:

type Product {
  media_gallery: [MediaGalleryEntry]
}

type MediaGalleryEntry {
  label: String
  position: Int
  disabled: Boolean
  file: String
}

 

Step 3: Write the GraphQL Query

Now, let's write the GraphQL query to fetch the product media gallery images URLs. We'll retrieve the product by its SKU and get the URLs of all the images in the media gallery. You can fetch the product media gallery images as well as the main Image, Thumbnail, Swatch Image, and Small Image URL by GraphQl.

query {
  products(filter: { sku: { eq: "YOUR_PRODUCT_SKU" } }) {
    items {
      swatch_image
      small_image {
        url
        label
        position
        disabled
      }
      thumbnail {
        url
        label
        position
        disabled
      }
      image {
        url
        label
        position
        disabled
      }
      media_gallery {
       url
        label
        position
        disabled
      }
    }
  }
}

Replace YOUR_PRODUCT_SKU with the SKU of the product you want to fetch the media gallery images URLs for.

Once you run the query, you will get the result as the URL of the product. If the specific image type is not found return it as null otherwise result will be a full product image URL.