Search code examples
node.jsgraphqlshopifynode-fetchshopify-api

How to get basic Shopify GraphQL Admin API working with nodeJS?


I had a very frustrating evening yesterday, trying to get the basic Shopify GraphQL Admin API example working with nodeJS. The original Shopify example code is here.

The problem is that my code returns a status 400 - Bad Request.

I have enabled a "private App" on my store and enabled all the APIs with read access. I carefully copied the apiKey, accessToken and store name from Shopify.

Can anyone point out if there is something wrong with my code? Many thanks.

Code:

import fetch from 'node-fetch';

const apiKey = 'xxxx';
const accessToken = 'yyyy';
const store = 'zzzz';
const hostName = store + '.myshopify.com';
const apiVersion = '2021-01';
const apiLocation = '/admin/api/';

const rootUrl = 'https://' + apiKey + ':' + accessToken + '@' + hostName + apiLocation + apiVersion + '/';

const shopGraphQl = 'https://' + hostName + apiLocation + apiVersion + '/graphql.json';
//const shopGraphQl2 = rootUrl + 'graphql.json';
//const urlTest = rootUrl + 'orders.json';

const url = shopGraphQl;

const body = {
    query: `{
        shop {
            name
          }
      }`
};

fetch   (
    url,
    {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-Shopify-Access-Token" : accessToken
        },
        body: JSON.stringify({
            body
        })
    }
)
.then(res => {
    console.log('status = ' + res.status + ' , ' + res.statusText);
})
.then(json => {
    console.log("data returned:\n", json);
})
.catch(err => console.error(err));; 

Solution

  • It looks like you are sending body incorrectly. The way you are sending your body results in {body: { query: { shop { name } } } }

    Instead of:

    body: JSON.stringify({body})
    

    change it to:

    body: JSON.stringify(body)
    

    Receiving data from fetch

    You have noticed that your console.log statement, console.log("data returned:\n", json); is returning undefined. The reason for this is that you need to extract the json from the response (res.json()).

    return fetch (
        url,
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-Shopify-Access-Token" : accessToken
            },
            body: JSON.stringify(body)
        }
    )
    .then(res => {
        console.log(`status = ${res.status}, ${res.statusText}`);
        return res.json();
    })
    .then(json => {
        console.log("data returned:\n", json);
    })
    .catch(err => console.error(err));; 
    

    Here is a decent reference on using fetch