- Node.js installed
shopify-api-node
package installed.env
file set up with your Shopify API credentials
Step 1: Install the required packages
npm install shopify-api-node dotenv axios
Step 2: Set up your .env
file
Create a .env
file in the root of your project with the following content:
SHOPIFY_SHOP_NAME=your-shop-name
SHOPIFY_API_KEY=your-api-key
SHOPIFY_PASSWORD=your-password
Step 3: Create the Node.js script
bulkFetchAndAddProducts.js
const Shopify = require('shopify-api-node')
const axios = require('axios')
require('dotenv').config()
const shopify = new Shopify({
shopName: process.env.SHOPIFY_SHOP_NAME,
apiKey: process.env.SHOPIFY_API_KEY,
password: process.env.SHOPIFY_PASSWORD
})
async function fetchProductsFromExternalSource() {
const url = 'https://external-source.com/api/products' // Replace with your external source URL
const response = await axios.get(url)
return response.data.products
}
async function addProductToShopify(product) {
const newProduct = {
title: product.title,
body_html: product.description,
vendor: product.vendor,
product_type: product.type,
tags: product.tags,
variants: product.variants.map(variant => ({
option1: variant.option1,
option2: variant.option2,
option3: variant.option3,
price: variant.price,
sku: variant.sku,
inventory_quantity: variant.inventory_quantity
})),
images: product.images.map(image => ({ src: image.src }))
}
try {
const createdProduct = await shopify.product.create(newProduct)
console.log(`Product created: ${createdProduct.id}`)
} catch (error) {
console.error(`Failed to create product: ${error.message}`)
}
}
async function bulkFetchAndAddProducts() {
try {
const products = await fetchProductsFromExternalSource()
for (const product of products) {
await addProductToShopify(product)
}
console.log('All products have been added to Shopify')
} catch (error) {
console.error(`Error fetching or adding products: ${error.message}`)
}
}
bulkFetchAndAddProducts()
Step 4: Run the script
node bulkFetchAndAddProducts.js
Explanation:
- Environment Variables: The script reads your Shopify credentials from the
.env
file. - Fetching Products: It fetches products from an external source using
axios
. - Adding Products: It iterates through the fetched products and adds them to Shopify using the
shopify-api-node
library.
This script provides a basic structure. You might need to adjust it based on the actual data structure from your external source and the specific requirements of your Shopify store.
Leave a Reply