Step-by-Step Guide
- Set Up Your Environment:
- Ensure you have
dotenv
andshopify-api-node
installed:
- Ensure you have
npm install dotenv shopify-api-node
Create Your .env
File:
- Create a
.env
file in the root of your project with your Shopify store details:
SHOPIFY_STORE=your-store-name.myshopify.com
SHOPIFY_ACCESS_TOKEN=your-access-token
- Create Your Script:
- Create a file, e.g.,
fetchProducts.js
, and add the following code:
- Create a file, e.g.,
require('dotenv').config()
const Shopify = require('shopify-api-node')
const shopify = new Shopify({
shopName: process.env.SHOPIFY_STORE,
accessToken: process.env.SHOPIFY_ACCESS_TOKEN
})
const fetchProducts = async () => {
const query = `
{
products(first: 10) {
edges {
node {
id
title
variants(first: 10) {
edges {
node {
id
title
price
}
}
}
}
}
}
}`
try {
const response = await shopify.graphql(query)
console.log('Products:', JSON.stringify(response, null, 2))
} catch (error) {
console.error('Error fetching products:', error)
}
}
fetchProducts()
Explanation
- Environment Variables: The
dotenv
package is used to load environment variables from the.env
file. - Shopify API Node: This package simplifies interaction with Shopify’s API.
- GraphQL Query: The query retrieves the first 10 products along with their variants’ details (id, title, and price).
- Error Handling: The
try-catch
block captures any errors during the API call and logs them.
Run the Script
To run the script, execute the following command in your terminal:
node fetchProducts.js
This will fetch the first 10 products from your Shopify store and log the details to the console.
Additional Considerations
- Pagination: If you need to fetch more products, you can handle pagination by using
cursor-based
pagination with theafter
argument in your query. - Error Handling: You may want to implement more robust error handling depending on your requirements.
- Data Processing: You can process or save the fetched data as needed within the
try
block.
By following these steps, you should be able to successfully fetch products from Shopify using the GraphQL API with Node.js. If you have any more questions or need further assistance, feel free to ask!
Leave a Reply