All Tutorials

Make GraphQL requests with Node and Express

All Tutorials

Make GraphQL requests with Node and Express

Make GraphQL requests with Node and Express

This tutorial will teach you how to use Shopify's GraphQL Admin API with Node and Express. After you've set up your project, you can try some GraphQL basics or update your app from REST to GraphQL.

In production, you should use a more powerful client, like Apollo, that automatically handles batching, caching and other features.

Requirements

Setup

To complete this tutorial you need a Shopify access token.

Create a Node.js project

  1. In a new console tab, create a directory named shopify-graphql-express-app and then run npm init from within the folder to create a package.json file:
Terminal
$ mkdir shopify-graphql-express-app
$ cd shopify-graphql-express-app
$ npm init -y
  1. Install the express and node-fetch packages.
Terminal
$ npm install express node-fetch --save

Create an express server

  1. Create a file named server.js, and then add the code below to setup a basic express server.
const express = require("express");
const fetch = require("node-fetch");

const app = express();

app.listen(3000, () => console.log("Listening on port 3000 .... "));
  1. Start your server.
Terminal
$ node server.js
  1. Stop your server with Ctrl+C.

Get shop information

  1. Add the following function to server.js, replacing <shop> with your shop's name and <access-token> with your access token.
app.get("/shop-info", (req, res) => {
  fetch("https://<shop>.myshopify.com/admin/api/graphql.json", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Shopify-Access-Token": "<access-token>"
    },
    body: JSON.stringify({
      query: `{
         shop {
           name
           url
           email
           myshopifyDomain
         }
       }`
    })
  })
    .then(result => {
      return result.json();
    })
    .then(data => {
      console.log("data returned:\n", data);
      res.send(data);
    });
});
  1. Start your server.
Terminal
$ node server.js
  1. Go to http://localhost:3000/shop-info to see the results of the query. You can install a JSON formatting extension to view the query results in your browser.

JSON response

{
  "data": {
    "shop": {
      "name": "johns-apparel",
      "url": "https://johns-apparel.myshopify.com",
      "email": "john@johns-apparel.com",
      "myshopifyDomain": "johns-apparel.myshopify.com"
    }
  },
  "extensions": {
    "cost": {
      "requestedQueryCost": 1,
      "actualQueryCost": 1,
      "throttleStatus": {
        "maximumAvailable": 1000,
        "currentlyAvailable": 999,
        "restoreRate": 50
      }
    }
  }
}

Get product info

To get a list of items such as your products, you need to add edges and nodes to your query. Think of edges as a way to access a group of objects and the node as the object within the group. The following code requests several product fields, including the ID. This ID is not the same as the REST ID. You can find more details about the GraphQL ID in our tutorial for translating from REST IDs to GraphQL IDs.

In this example, you are passing a $query: String! and a $num: Int!. The exclamation point indicates that they are required arguments. Arguments are defined in the query declaration, and can then be used inside the query.

  1. Add the following function to server.js. Replace <shop> with your shop's name and <access-token> with your access token, and then restart the server.
app.get("/products", (req, res) => {
  fetch("https://<shop>.myshopify.com/admin/api/graphql.json", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Shopify-Access-Token": "<access-token>"
    },
    body: JSON.stringify({
      query: `query findProducts($query: String!, $num: Int!) {
         shop {
           name
         }
         products(first: $num, query: $query) {
           edges {
             cursor
             node {
               id
               title
               featuredImage {
                 originalSrc
               }
               totalInventory
             }
           }
         }
       }`,
      variables: { query: "necklace", num: 5 }
    })
  })
    .then(result => {
      return result.json();
    })
    .then(data => {
      console.log("data returned:\n", data);
      res.send(data);
    });
});
  1. Go to http://localhost:3000/products to see the query results.

JSON response

{
  "data": {
    "shop": {
      "name": "johns-apparel"
    },
    "products": {
      "edges": [
        {
          "cursor": "eyJsYXN0X2lkIjoxNTU2MTk0OPUxMjI0LCJsYXN0X3ZhbHVlIjoxNTU2MTk0OTUxMjI0fQ==",
          "node": {
            "id": "gid://shopify/Product/1556194951225",
            "title": "Unicorn Necklace Gold",
            "featuredImage": {
              "originalSrc": "https://cdn.shopify.com/s/files/1/0046/2608/7992/products/Gold_Unicorn.jpeg?v=1578434925"
            },
            "totalInventory": 3381
          }
        },
        {
          "cursor": "eyJsYXN0X2lkIjoxNTU2MTk1MDE2NzYwLAJsYXN0X3ZhbHVlIjoxNTU2MTk1MDE2NzYwfQ==",
          "node": {
            "id": "gid://shopify/Product/1556195016762",
            "title": "Unicorn Necklace Silver",
            "featuredImage": {
              "originalSrc": "https://cdn.shopify.com/s/files/1/0046/2608/7992/products/Unicorn_Silver_Necklace.jpeg?v=1578434925"
            },
            "totalInventory": 538
          }
        }
      ]
    }
  },
  "extensions": {
    "cost": {
      "requestedQueryCost": 13,
      "actualQueryCost": 7,
      "throttleStatus": {
        "maximumAvailable": 1000,
        "currentlyAvailable": 993,
        "restoreRate": 50
      }
    }
  }
}

Congratulations, you’ve just made an app that pulls data from Shopify’s GraphQL API!

Next steps

Implementing GraphQL using the Apollo client.

Need help?

If you can’t get something to work, then check the GraphQL with Node and Express community forum post for help.