Explained: Top 10 Tips to Utilize Shopify GraphQL API

Jennie Lee
5 min readMar 16, 2024

--

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Explained: Top 10 Tips to Utilize Shopify GraphQL API

Introduction to the Shopify GraphQL API

The Shopify GraphQL API is a powerful tool for interacting with a Shopify store and retrieving data. GraphQL is a query language that allows you to request and retrieve specific data from a server, making it a more efficient and flexible alternative to traditional REST APIs. With the Shopify GraphQL API, you can fetch products, retrieve customer information, manage orders, and perform various other tasks.

When it comes to integrating the Shopify GraphQL API into your application, using Node.js is highly recommended. Node.js is a popular runtime environment for executing JavaScript code and has excellent support for working with GraphQL. Node.js provides a seamless environment for executing GraphQL queries, handling the responses, and performing any necessary data manipulation or processing.

Before diving into the implementation, it’s important to note that this tutorial assumes that you have a basic understanding of GraphQL and have completed the Shopify Learning GraphQL workshop. Additionally, make sure you have installed the necessary Node.js packages using npm for this tutorial.

Setting Up the Project and Accessing the Shopify Store

The first step in utilizing the Shopify GraphQL API is to set up your project and access your Shopify store. To do this, create a .env file in your project directory and add the Shopify store URL and access token to it. The access token is crucial as it is required to access the Shopify Admin API.

# .env
SHOPIFY_STORE_URL=https://your-store-url.myshopify.com
SHOPIFY_ACCESS_TOKEN=your-access-token

Note: It’s important to keep your access token secure and not expose it in public repositories or insecure environments.

Fetching Products Using Node.js and GraphQL

Now that you have set up the project and obtained the Shopify store URL and access token, we can start fetching products from the Shopify store using Node.js and GraphQL. In your project directory, create a JavaScript file named fetchProducts.js.

Start by importing the necessary packages at the beginning of the file:

const fetch = require('node-fetch');
const dotenv = require('dotenv');

// Load environment variables from .env file
dotenv.config();

Next, set the GraphQL endpoint to your Shopify store:

const graphqlEndpoint = `${process.env.SHOPIFY_STORE_URL}/api/2021-04/graphql.json`;

Now, define the GraphQL query to fetch the products. In this example, we will fetch the first 5 products:

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

To make a GraphQL request to Shopify, we will use the node-fetch package. Use the fetch function to send the GraphQL query to the Shopify GraphQL endpoint and pass the access token as a bearer token in the request headers:

fetch(graphqlEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': process.env.SHOPIFY_ACCESS_TOKEN
},
body: JSON.stringify({ query })
})

Finally, log the response to the console:

.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Running the Script and Displaying Product Information

To run the fetchProducts.js script, open the terminal and navigate to your project directory. Run the following command:

node fetchProducts.js

This will execute the script and fetch the first 5 products from your Shopify store. The returned data will be logged to the console.

The response structure will include detailed information about the fetched products, such as the product ID, title, description, and the price of the first variant. It’s important to understand the response structure and how to extract specific data from it for further processing or displaying purposes.

Creating an API Endpoint with Express.js (Advanced Option)

If you want to build an API endpoint using Express.js to fetch products from your Shopify store, follow these steps:

  1. Install the express and node-fetch packages by running the following command in your project directory:
npm install express node-fetch
  1. Create an app.js file in your project directory.
  2. In the app.js file, import the necessary packages and set up an Express server:
const express = require('express');
const fetch = require('node-fetch');
const dotenv = require('dotenv');

// Load environment variables from .env file
dotenv.config();

const app = express();
const port = 3000;

app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
  1. Define a route for fetching the products. This route will make a GraphQL request to your Shopify store and return a JSON response with the product information:
app.get('/products', (req, res) => {
const graphqlEndpoint = `${process.env.SHOPIFY_STORE_URL}/api/2021-04/graphql.json`;

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

fetch(graphqlEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': process.env.SHOPIFY_ACCESS_TOKEN
},
body: JSON.stringify({ query })
})
.then(response => response.json())
.then(data => res.json(data))
.catch(error => res.json({ error: error.message }));
});
  1. Save the app.js file and start the server by running the following command in your project directory:
node app.js
  1. Now, accessing the /products route, either through a browser or an HTTP request tool, will return a JSON response with the fetched product information.

Bonus Tip: Obtaining the Shopify Access Token

To obtain the Shopify access token for your Shopify store, you need to create a private app in the Shopify admin section. Here’s how:

  1. Log in to your Shopify admin and go to the “Apps” section.
  2. Click on “Manage private apps” and then click on “Create a new private app.”
  3. Fill in the required details, such as app name and email address.
  4. Under the “Admin API” section, enable the necessary permissions for accessing products, orders, customers, or any other resources you need.
  5. Save the app and a unique access token will be generated for you. Make sure to copy and securely store the access token as it will be required to access the Shopify Admin API.

In conclusion, utilizing the Shopify GraphQL API with Node.js provides a powerful and efficient way to interact with your Shopify store. By following the steps outlined in this tutorial, you’ll be able to fetch products from your Shopify store, whether it’s for retrieving data or building an API endpoint. Remember to always handle your access token securely and avoid exposing it in public repositories or insecure environments.

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--

Jennie Lee
Jennie Lee

Written by Jennie Lee

Software Testing Blogger, #API Testing

No responses yet