How to Fetch Shopify Products Using GraphQL API in Node.js | Shopify Tutorial

As e-commerce continues to evolve, developers are increasingly required to integrate various tools and platforms to create seamless, efficient workflows. Shopify, one of the leading e-commerce platforms, offers a powerful API that allows developers to interact programmatically with a Shopify store’s data. In this tutorial, we’ll explore how to fetch Shopify products using the GraphQL API in a Node.js environment. Whether you’re building a custom Shopify app or simply automating tasks, understanding how to use Shopify’s GraphQL API is essential.

Why Use Shopify’s GraphQL API?

Before diving into the implementation, it’s important to understand the advantages of using Shopify’s GraphQL API:

  • Efficiency: GraphQL allows you to request only the data you need, reducing the amount of data transferred over the network and improving the performance of your application.
  • Flexibility: With GraphQL, you can fetch related data in a single request, making it easier to handle complex data structures.
  • Scalability: GraphQL is well-suited for large-scale applications where multiple data points need to be retrieved and managed efficiently.

Prerequisites

Before starting, make sure you have the following prerequisites:

  • Node.js and npm: Ensure Node.js and npm (Node Package Manager) are installed on your machine. You can download them from the official Node.js website.
  • Shopify Store: You need access to a Shopify store to connect to the Shopify API.
  • Shopify Admin API Access: Ensure you have API credentials (API key, secret, and access token) to interact with Shopify’s Admin API.

Step 1: Setting Up Your Node.js Project

The first step is to set up a new Node.js project that will handle API requests to Shopify.

Initialize a New Node.js Project

Create a new directory for your project and navigate into it:

bashCopy codemkdir shopify-fetch-products
cd shopify-fetch-products

Initialize a new Node.js project:

bashCopy codenpm init -y

This command creates a package.json file, which tracks your project’s dependencies and scripts.

Install Required Packages

Next, install the necessary npm packages for your project:

bashCopy codenpm install axios dotenv express
  • axios: A promise-based HTTP client for making API requests.
  • dotenv: A module that loads environment variables from a .env file into process.env.
  • express: A minimal and flexible Node.js web application framework.

Step 2: Configure Environment Variables

Create a .env file in the root directory of your project to store sensitive information:

bashCopy codeSHOPIFY_API_KEY=your-shopify-api-key
SHOPIFY_API_SECRET=your-shopify-api-secret
SHOPIFY_ACCESS_TOKEN=your-shopify-access-token
SHOPIFY_STORE=my-shop-name.myshopify.com

Replace the placeholder values with your actual Shopify credentials. These credentials are necessary to authenticate your requests to the Shopify API.

Step 3: Create a GraphQL Query to Fetch Products

With your environment set up, the next step is to write a script that fetches products from Shopify using the GraphQL API.

Create the Product Fetching Script

In your project directory, create a new file named fetchProducts.js. This script will use the Shopify GraphQL API to retrieve a list of products:

javascriptCopy coderequire('dotenv').config();
const axios = require('axios');

const fetchShopifyProducts = async () => {
  const url = `https://${process.env.SHOPIFY_STORE}/admin/api/2023-01/graphql.json`;

  const query = `
    {
      products(first: 10) {
        edges {
          node {
            id
            title
            descriptionHtml
            variants(first: 5) {
              edges {
                node {
                  id
                  title
                  price
                }
              }
            }
            images(first: 1) {
              edges {
                node {
                  src
                }
              }
            }
          }
        }
      }
    }
  `;

  try {
    const response = await axios.post(url, { query }, {
      headers: {
        'X-Shopify-Access-Token': process.env.SHOPIFY_ACCESS_TOKEN,
        'Content-Type': 'application/json'
      }
    });

    const products = response.data.data.products.edges.map(edge => edge.node);
    console.log('Fetched products:', products);
  } catch (error) {
    console.error('Error fetching products:', error.response ? error.response.data : error.message);
  }
};

fetchShopifyProducts();

In this code:

  • axios.post(): Sends a POST request to the Shopify GraphQL API to fetch product data.
  • query: A GraphQL query that requests the first 10 products, including their IDs, titles, descriptions, variants, and images.

Step 4: Running the Script

To fetch the products, simply run the fetchProducts.js script:

bashCopy codenode fetchProducts.js

If the request is successful, the script will log the fetched products to the console. If there’s an error, the script will log the error message.

Step 5: Setting Up an Express Server to Display Products

Now that you can fetch products from Shopify, let’s set up an Express server to display these products.

Create the Express Server

Create a new file named server.js and add the following code:

javascriptCopy codeconst express = require('express');
const fetchShopifyProducts = require('./fetchProducts');

const app = express();
const port = process.env.PORT || 3000;

app.get('/products', async (req, res) => {
  try {
    const products = await fetchShopifyProducts();
    res.json(products);
  } catch (error) {
    res.status(500).send('Error fetching products');
  }
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

In this code:

  • Express Server: Sets up an Express server that listens for GET requests to the /products endpoint.
  • fetchShopifyProducts: The function you created earlier is used to fetch products from Shopify, and the data is returned as JSON.

Step 6: Running the Server and Testing the Endpoint

With everything in place, you can now run your Node.js application and test the endpoint.

Start the Server

Start your Express server by running the following command:

bashCopy codenode server.js

Your server should now be running on http://localhost:3000/products.

Test the Endpoint

Open a web browser or use a tool like Postman to navigate to http://localhost:3000/products. You should see a JSON response containing the list of products fetched from your Shopify store.

Step 7: Expanding Functionality

Now that you have the basic functionality to fetch and display Shopify products using Node.js and the GraphQL API, you can expand your application in various ways:

  1. Pagination: Implement pagination to handle large datasets, allowing users to navigate through pages of products.
  2. Filtering and Sorting: Add query parameters to filter products by category, price, or availability, and sort them by various criteria.
  3. Detailed Product View: Create a route that displays detailed information for a single product, including all variants, images, and descriptions.
  4. Product Management Interface: Build a web interface using a front-end framework like React or Vue.js to allow users to manage products through a GUI.

Best Practices

When working with the Shopify GraphQL API, consider the following best practices:

  • Error Handling: Implement robust error handling to deal with potential issues such as network errors, invalid API requests, or authentication failures.
  • Rate Limiting: Be mindful of Shopify’s API rate limits to avoid being throttled. Implement retry mechanisms if your app makes many requests.
  • Security: Secure your API keys and access tokens by storing them in environment variables and never hard-coding them in your source code.

Conclusion

By following this tutorial, you’ve learned how to fetch Shopify products using the GraphQL API in Node.js. This integration allows you to build powerful custom apps that interact with Shopify’s data in real-time, providing valuable insights and automation capabilities for your e-commerce store.

As you continue to develop with Shopify, consider exploring more advanced features of the GraphQL API, such as filtering products by specific attributes, fetching collections, or even managing inventory. Whether you’re building simple data retrieval tools or complex e-commerce solutions, mastering the Shopify GraphQL API with Node.js will open up a world of possibilities for your development projects.

Leave a Reply

Your email address will not be published. Required fields are marked *