How to Fetch and Display Shopify Orders Using GraphQL API in Node.js | Shopify Tutorial

Shopify is a powerful e-commerce platform that provides developers with a robust API to interact with its data. Whether you’re building a custom Shopify app or integrating Shopify with other systems, being able to fetch and display Shopify orders using the GraphQL API is a crucial skill. In this tutorial, we’ll walk you through the process of setting up a Node.js application to retrieve and display Shopify orders using the GraphQL API. By the end of this guide, you’ll have a solid understanding of how to work with Shopify’s GraphQL API and integrate it into your Node.js projects.

Why Use Shopify’s GraphQL API?

Before we dive into the tutorial, let’s briefly discuss why you might choose Shopify’s GraphQL API over its REST API:

  • Efficiency: GraphQL allows you to request only the data you need, reducing the amount of data transferred over the network and improving performance.
  • Flexibility: With GraphQL, you can fetch related data in a single request, making it easier to work with complex data structures.
  • Real-Time Queries: GraphQL provides a more interactive and efficient way to query data, especially useful for dynamic e-commerce applications.

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 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-orders
cd shopify-fetch-orders

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 that provides a robust set of features for web and mobile applications.

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 Orders

Now that your environment is set up, let’s write a script to fetch orders from Shopify using the GraphQL API.

Create the Fetch Orders Script

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

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

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

  const query = `
    {
      orders(first: 10) {
        edges {
          node {
            id
            name
            totalPriceSet {
              shopMoney {
                amount
              }
            }
            createdAt
            lineItems(first: 5) {
              edges {
                node {
                  title
                  quantity
                }
              }
            }
            customer {
              firstName
              lastName
              email
            }
          }
        }
      }
    }
  `;

  try {
    const response = await axios.post(url, { query }, {
      headers: {
        'X-Shopify-Access-Token': process.env.SHOPIFY_ACCESS_TOKEN,
        'Content-Type': 'application/json'
      }
    });
    return response.data.data.orders.edges.map(edge => edge.node);
  } catch (error) {
    console.error('Error fetching orders:', error.response ? error.response.data : error.message);
  }
};

module.exports = fetchShopifyOrders;

In this code:

  • axios.post(): Sends a POST request to the Shopify GraphQL API to fetch the orders.
  • query: A GraphQL query that requests the first 10 orders, including details like order ID, name, total price, creation date, line items, and customer information.

Step 4: Display Orders Using Express

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

Create the Express Server

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

javascriptCopy codeconst express = require('express');
const fetchShopifyOrders = require('./fetchOrders');

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

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

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 /orders endpoint.
  • fetchShopifyOrders: The function you previously created is used to fetch orders from Shopify, and the data is returned as JSON.

Step 5: Run and Test Your Application

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

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/orders.

Test the Endpoint

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

Step 6: Expanding Functionality

Now that you have the basic functionality to fetch and display Shopify orders 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 orders.
  2. Filtering and Sorting: Add query parameters to filter orders by date, status, or customer, and sort them by total price or creation date.
  3. Detailed Order View: Create a route that displays detailed information for a single order, including all line items, customer details, and fulfillment status.
  4. Order Processing Automation: Integrate this application with other services like fulfillment centers, CRMs, or accounting software to automate order processing workflows.

Best Practices

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

  • Error Handling: Always implement robust error handling to deal with potential issues such as rate limiting, network errors, or invalid API requests.
  • Rate Limits: Be aware of Shopify’s API rate limits to avoid being throttled. Implement exponential backoff or 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 and display Shopify orders 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 subscriptions for real-time updates or mutations to create and update data. 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 *