Shopify API: Bulk Fetch and Add Products with Node.js | Shopify Tutorial

Managing a Shopify store with a large inventory can be a time-consuming task, especially when you need to add or update multiple products at once. Fortunately, Shopify’s API allows developers to automate this process by bulk fetching and adding products using Node.js. In this tutorial, we’ll guide you through the process of using Node.js to interact with the Shopify API, enabling you to efficiently manage large quantities of products. Whether you’re migrating products from another platform or updating your existing catalog, this guide will help you streamline your e-commerce operations.

Why Use Shopify API for Bulk Operations?

The Shopify API provides a powerful way to manage your store programmatically. Using the API for bulk operations offers several benefits:

  • Efficiency: Automating the process of fetching and adding products saves time and reduces the likelihood of human error.
  • Scalability: The API allows you to handle large datasets, making it easier to manage a growing product catalog.
  • Integration: You can integrate Shopify with external systems, such as ERPs or inventory management tools, to keep your store up-to-date.

Prerequisites

Before starting, ensure you have the following prerequisites:

  • Node.js and npm: Make sure 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 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-bulk-operations
cd shopify-bulk-operations

Initialize a new Node.js project:

bashCopy codenpm init -y

This command creates a package.json file that 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: Bulk Fetch Products from Shopify

Fetching a large number of products from Shopify can be done efficiently using the API. Let’s write a script that retrieves products in bulk.

Create the Fetch Products Script

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

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

const fetchShopifyProducts = async () => {
  const url = `https://${process.env.SHOPIFY_STORE}/admin/api/2023-01/products.json`;
  let products = [];
  let pageInfo = null;

  try {
    do {
      const response = await axios.get(url, {
        headers: {
          'X-Shopify-Access-Token': process.env.SHOPIFY_ACCESS_TOKEN,
          'Content-Type': 'application/json'
        },
        params: {
          limit: 250, // Maximum limit per request
          page_info: pageInfo
        }
      });

      products = products.concat(response.data.products);

      pageInfo = response.headers['link'] ? extractPageInfo(response.headers['link']) : null;
    } while (pageInfo);

    console.log('Total products fetched:', products.length);
    console.log(products);
  } catch (error) {
    console.error('Error fetching products:', error.response ? error.response.data : error.message);
  }
};

const extractPageInfo = (linkHeader) => {
  const matches = linkHeader.match(/page_info=([^&>]+).rel="next"/);
  return matches ? matches[1] : null;
};

fetchShopifyProducts();

In this code:

  • axios.get(): Sends a GET request to Shopify’s API to fetch products.
  • pageInfo: Handles pagination by storing the page_info parameter to fetch the next batch of products.
  • limit: Limits the number of products fetched per request to 250 (the maximum allowed by Shopify).

Step 4: Bulk Add Products to Shopify

Now, let’s write a script that adds multiple products to Shopify in bulk.

Create the Add Products Script

In your project directory, create a new file named addProducts.js. This script will use the Shopify API to add multiple products:

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

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

  try {
    for (let product of products) {
      const productData = {
        product: {
          title: product.title,
          body_html: product.description,
          vendor: product.vendor,
          product_type: product.type,
          variants: product.variants,
          images: product.images
        }
      };

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

      console.log('Product added successfully:', response.data.product.id);
    }
  } catch (error) {
    console.error('Error adding product:', error.response ? error.response.data : error.message);
  }
};

// Example product data to add
const products = [
  {
    title: "Sample Product 1",
    description: "<strong>Good quality</strong> product",
    vendor: "Vendor 1",
    type: "Type 1",
    variants: [
      {
        option1: "Default Title",
        price: "19.99",
        sku: "SAMPLE-001",
        inventory_quantity: 100
      }
    ],
    images: [
      {
        src: "https://example.com/image1.jpg"
      }
    ]
  },
  // Add more products here
];

addProducts(products);

In this code:

  • productData: Contains the necessary data to create a product in Shopify, including title, description, vendor, type, variants, and images.
  • axios.post(): Sends a POST request to Shopify’s API to add each product.

Step 5: Combining Fetch and Add Operations for Product Integration

You can combine the fetch and add operations to migrate products from one Shopify store to another or to synchronize product data with an external system.

Example: Fetch and Add Products

Create a new file named migrateProducts.js that combines both scripts:

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

const fetchShopifyProducts = async () => {
  const url = `https://${process.env.SHOPIFY_STORE}/admin/api/2023-01/products.json`;
  let products = [];
  let pageInfo = null;

  try {
    do {
      const response = await axios.get(url, {
        headers: {
          'X-Shopify-Access-Token': process.env.SHOPIFY_ACCESS_TOKEN,
          'Content-Type': 'application/json'
        },
        params: {
          limit: 250,
          page_info: pageInfo
        }
      });

      products = products.concat(response.data.products);

      pageInfo = response.headers['link'] ? extractPageInfo(response.headers['link']) : null;
    } while (pageInfo);

    return products;
  } catch (error) {
    console.error('Error fetching products:', error.response ? error.response.data : error.message);
  }
};

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

  try {
    for (let product of products) {
      const productData = {
        product: {
          title: product.title,
          body_html: product.body_html,
          vendor: product.vendor,
          product_type: product.product_type,
          variants: product.variants,
          images: product.images
        }
      };

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

      console.log('Product added successfully:', response.data.product.id);
    }
  } catch (error) {
    console.error('Error adding product:', error.response ? error.response.data : error.message);
  }
};

const migrateProducts = async () => {
  const products = await fetchShopifyProducts();
  if (products) {
    await addProducts(products);
  }
};

migrateProducts();

Best Practices

When working with Shopify’s API for bulk operations, consider the following best practices:

Leave a Reply

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