Using GraphQL Admin API with GatsbyJS

Highlighted
New Member
5 0 0

Summary

I’m working on sourcing and combining data from Shopify Storefront and GraphQL Admin APIs into Gatsby. For sourcing Storefront API I use gatsby-source-shopify, though I wasn’t able to find source plugin for _Shopify Admin API_ and ended up using gatsby-source-graphql. I have created a private Shopify app and granted all permissions and was able to fetch data using curl example from Shopify GraphQL Admin API documentation.

This issue can also be found on GitHub and StackOverflow  

 

curl -X POST \
"https://shop-name.myshopify.com/admin/api/2019-04/graphql.json" \
-H "Content-Type: application/graphql" \
-H "X-Shopify-Access-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-d '
{
  shop {
    name
  }
}
'


Output:

{"data":{"shop":{"name":"Shop Name"}},"extensions":{"cost":{"requestedQueryCost":1,"actualQueryCost":1,"throttleStatus":{"maximumAvailable":1000.0,"currentlyAvailable":999,"restoreRate":50.0}}}}


Relevant information

Error message:

 

success open and validate gatsby-configs — 0.008 s
success load plugins — 0.354 s
success onPreInit — 0.006 s
success initialize cache — 0.012 s
success copy gatsby files — 0.075 s
success onPreBootstrap — 0.006 s
error Plugin gatsby-source-graphql returned an error


  ServerError: Response not successful: Received status code 400

  - index.js:23 Object.exports.throwServerError
    [gatsby-shopify-starter]/[apollo-link-http-common]/lib/index.js:23:17

  - index.js:48
    [gatsby-shopify-starter]/[apollo-link-http-common]/lib/index.js:48:21

  - next_tick.js:77 process.internalTickCallback
    internal/process/next_tick.js:77:7



gatsby-source-shopify/new-dev-sandbox starting to fetch data from Shopify

gatsby-source-shopify/new-dev-sandbox fetched and processed blogs: 310.223ms

gatsby-source-shopify/new-dev-sandbox fetched and processed productTypes: 319.782ms

gatsby-source-shopify/new-dev-sandbox fetched and processed policies: 385.070ms

gatsby-source-shopify/new-dev-sandbox fetched and processed articles: 553.907ms

gatsby-source-shopify/new-dev-sandbox fetched and processed collections: 19657.714ms


gatsby-source-shopify/new-dev-sandbox fetched and processed products: 23834.024ms

gatsby-source-shopify/new-dev-sandbox finished fetching data from Shopify: 23841.033ms
warning The gatsby-source-graphql plugin has generated no Gatsby nodes. Do you need it?
success source and transform nodes — 24.504 s
warning Multiple node fields resolve to the same GraphQL field `ShopifyCollection.products` - [`products`, `products___NODE`]. Gatsby will use `products___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyProduct.options` - [`options`, `options___NODE`]. Gatsby will use `options___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyProduct.variants` - [`variants`, `variants___NODE`]. Gatsby will use `variants___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyArticle.blog` - [`blog`, `blog___NODE`]. Gatsby will use `blog___NODE`.
success building schema — 0.261 s
success createPages — 0.000 s
success createPagesStatefully — 0.042 s
success onPreExtractQueries — 0.005 s
success update schema — 0.019 s
error GraphQL Error Encountered 1 error(s):
- Unknown field 'admin' on type 'Query'.

      file: /Users/skok/dev/gatsby-shopify-starter/src/components/collections.js



success extract queries from components — 0.107 s
success run static queries — 0.001 s
error (node:18142) DeprecationWarning: Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.
success run page queries — 0.012 s — 4/4 338.87 queries/second
success write out page data — 0.011 s
success write out redirect data — 0.003 s
success Build manifest and related icons — 0.114 s
success onPostBootstrap — 0.116 s

info bootstrap finished - 27.312 s

 ERROR  Failed to compile with 1 errors                                                                                                                                                           9:03:26 PM

 error  in ./src/components/collections.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
  43:7  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)


 @ ./src/pages/index.js 10:0-52 25:37-48
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app

error ✖ 「wdm」:
ERROR in ./src/components/collections.js
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
  43:7  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)

 @ ./src/pages/index.js 10:0-52 25:37-48
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app
info ℹ 「wdm」: Failed to compile.
 WAIT  Compiling...                                                                                                                                                                               9:03:26 PM

info ℹ 「wdm」: Compiling...
 ERROR  Failed to compile with 1 errors                                                                                                                                                           9:03:27 PM

 error  in ./src/components/collections.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
  43:7  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)


 @ ./src/pages/index.js 10:0-52 25:37-48
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app

error ✖ 「wdm」:
ERROR in ./src/components/collections.js
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
  43:7  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)

 @ ./src/pages/index.js 10:0-52 25:37-48
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app
info ℹ 「wdm」: Failed to compile.
 WAIT  Compiling...                                                                                                                                                                               9:03:44 PM

info ℹ 「wdm」: Compiling...
error GraphQL Error Encountered 1 error(s):
- Unknown field 'admin' on type 'Query'.

      file: /Users/skok/dev/gatsby-shopify-starter/src/components/collections.js



 ERROR  Failed to compile with 1 errors                                                                                                                                                           9:03:45 PM

 error  in ./src/components/collections.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
   5:9  warning  'storefrontData' is assigned a value but never used  no-unused-vars
  41:9  warning  'adminData' is assigned a value but never used       no-unused-vars
  43:7  error    Cannot query field "admin" on type "Query"           graphql/template-strings

✖ 3 problems (1 error, 2 warnings)


 @ ./src/pages/index.js 10:0-52 25:37-48
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app

error ✖ 「wdm」:
ERROR in ./src/components/collections.js
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
   5:9  warning  'storefrontData' is assigned a value but never used  no-unused-vars
  41:9  warning  'adminData' is assigned a value but never used       no-unused-vars
  43:7  error    Cannot query field "admin" on type "Query"           graphql/template-strings

✖ 3 problems (1 error, 2 warnings)

 @ ./src/pages/index.js 10:0-52 25:37-48
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app
info ℹ 「wdm」: Failed to compile.

 


gatsby-config.js

import React from 'react'
import Layout from '../components/layout'
import Collections from '../components/collections'

const IndexPage = () => (
  <Layout>
    <h1>Shopify</h1>
    <Collections />
  </Layout>
)

export default IndexPage

 

 

./src/collections.js

import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'

const Collections = () => {
  const storefrontData = useStaticQuery(
    graphql`
      query {
        allShopifyCollection {
          edges {
            node {
              id
              description
              descriptionHtml
              handle
              image {
                altText
                id
                src
                localFile {
                  childImageSharp {
                    fluid(maxWidth: 910) {
                      ...GatsbyImageSharpFluid_withWebp_tracedSVG
                    }
                  }
                }
              }
              products {
                id
                handle
                title
              }
              title
              updatedAt
            }
          }
        }
      }
    `
  )

  const adminData = useStaticQuery(graphql`
    query {
      admin {
        shop {
          name
        }
      }
    }
  `)

  return (
    <div className="collections">
      Collections
    </div>
  )
}

export default Collections


index.js

import React from 'react'
import Layout from '../components/layout'
import Collections from '../components/collections'

const IndexPage = () => (
  <Layout>
    <h1>Shopify</h1>
    <Collections />
  </Layout>
)

export default IndexPage

package.json

 

{
  "name": "gatsby-shopify",
  "private": true,
  "description": "Gatsby Shopify Starter",
  "version": "0.1.0",
  "author": "Vladimir Skok <skok@vova.io>",
  "dependencies": {
    "gatsby": "^2.4.2",
    "gatsby-image": "^2.0.41",
    "gatsby-plugin-manifest": "^2.1.1",
    "gatsby-plugin-offline": "^2.1.0",
    "gatsby-plugin-react-helmet": "^3.0.12",
    "gatsby-plugin-sharp": "^2.0.36",
    "gatsby-source-filesystem": "^2.0.33",
    "gatsby-source-graphql": "^2.0.18",
    "gatsby-source-shopify": "^2.0.28",
    "gatsby-transformer-sharp": "^2.1.19",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-helmet": "^5.2.1"
  },
  "devDependencies": {
    "prettier": "^1.17.0"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write src/**/*.{js,jsx}",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/iamskok/gatsby-shopify-starter"
  },
  "bugs": {
    "url": "https://github.com/iamskok/gatsby-shopify-starter/issues"
  }
}

 

 

0 Likes
Shopify Staff
Shopify Staff
1555 79 241

Looking at your stack trace, it looks like you're trying to access an admin object on the query root, and looking for a shop object connected to that? I might just be misinterpreting how gatsby-source-graphql works but this query would not work against the GraphQL Admin API:

 

query {
  admin {
    shop {
      name
    }
  }
}

... you would instead just access the shop object directly:

 

query {
  shop {
    name
  }
}

Just make sure you're hitting the graphql admin API via https://shop.myshopify.com/admin/api/graphql.json rather than https://shop.myshopify.com/api/graphql.

 

Hope that helps, let me know if I'm misunderstanding the question.

0 Likes
New Member
5 0 0

@Alex here is a github repo with all the code from below https://github.com/iamskok/example-gatsby-shopify-admin

 

Here is my gatsby-config.js. 

gatsby-source-graphql   plugin is supposed to work with GraphQL Admin API.

 

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`
});

module.exports = {
  siteMetadata: {
    title: `Gatsby-shopify`,
    description: `Gatsby Shopify Starter.`,
    author: `@iamskok`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: "gatsby-source-graphql",
      options: {
        typeName: "ShopifyAdmin",
        fieldName: "admin",
        url: `https://${process.env.SHOP_NAME}.myshopify.com/admin/api/graphql.json`,
        headers: {
          'X-Shopify-Access-Token': `${process.env.ADMIN_PASSWORD}`,
        },
        fetchOptions: {
          method: 'POST'
        },
        refetchInterval: 60
      },
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
  ],
}

This is my component which has GraphQL query:

 

import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'

const Collections = () => {
  const data = useStaticQuery(
    graphql`
      query {
        shop {
          name
        }
      }
    `
  );

  console.log('data:', JSON.stringify(data));

  return (
    <div className="collections">
      <h2>Collections</h2>
    </div>
  )
}

export default Collections

This query results in 

 

error Plugin gatsby-source-graphql returned an error


  Error: Schema must contain uniquely named types but contains multiple types named "QueryRoot".

  - Array.reduce

  - transforms.js:56 NamespaceUnderFieldTransform.transformSchema
    [bva-gatsby-shopify-starter]/[gatsby-source-graphql]/transforms.js:56:12

  - transforms.js:5
    [bva-gatsby-shopify-starter]/[graphql-tools]/dist/transforms/transforms.js:5:54

  - Array.reduce

  - transforms.js:4 Object.applySchemaTransforms
    [bva-gatsby-shopify-starter]/[graphql-tools]/dist/transforms/transforms.js:4:23

  - transformSchema.js:18 transformSchema
    [bva-gatsby-shopify-starter]/[graphql-tools]/dist/transforms/transformSchema.js:18:27

  - gatsby-node.js:107 Object.<anonymous>
    [bva-gatsby-shopify-starter]/[gatsby-source-graphql]/gatsby-node.js:107:20

  - Generator.next


success source and transform nodes — 2.859 s
success building schema — 0.176 s
success createPages — 0.000 s
success createPagesStatefully — 0.040 s
success onPreExtractQueries — 0.002 s
success update schema — 0.017 s
error GraphQL Error Encountered 1 error(s):
- Unknown field 'admin' on type 'Query'.

      file: /Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js



success extract queries from components — 0.105 s
success run static queries — 0.001 s
error (node:53813) DeprecationWarning: Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.
success run page queries — 0.008 s — 4/4 525.13 queries/second
success write out page data — 0.004 s
success write out redirect data — 0.001 s
success Build manifest and related icons — 0.105 s
success onPostBootstrap — 0.106 s

info bootstrap finished - 5.409 s

 ERROR  Failed to compile with 1 errors                                                   12:34:02 PM

 error  in ./src/components/collections.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)


 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app

error ✖ 「wdm」:
ERROR in ./src/components/collections.js
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)

 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app
info ℹ 「wdm」: Failed to compile.
 WAIT  Compiling...                                                                       12:34:02 PM

info ℹ 「wdm」: Compiling...
 ERROR  Failed to compile with 1 errors                                                   12:34:02 PM

 error  in ./src/components/collections.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)


 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app

error ✖ 「wdm」:
ERROR in ./src/components/collections.js
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)

 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app
info ℹ 「wdm」: Failed to compile.

I initially used `admin` field, bc I was under the expression that I have to use whatever fieldName I defined in the config.

`gatsby-source-graphql` is a plugin for connecting arbitrary GraphQL APIs to Gatsby GraphQL. Remote schemas are stitched together by adding a type that wraps the remote schema Query type and putting it under field of Gatsby GraphQL Query.

 

query {
  admin {
    shop {
      name
    }
  }
}

 

With the above query I get:

 

success open and validate gatsby-configs — 0.008 s
success load plugins — 0.313 s
success onPreInit — 0.005 s
success initialize cache — 0.013 s
success copy gatsby files — 0.073 s
success onPreBootstrap — 0.006 s
error Plugin gatsby-source-graphql returned an error


  Error: Schema must contain uniquely named types but contains multiple types named "QueryRoot".

  - Array.reduce

  - transforms.js:56 NamespaceUnderFieldTransform.transformSchema
    [bva-gatsby-shopify-starter]/[gatsby-source-graphql]/transforms.js:56:12

  - transforms.js:5
    [bva-gatsby-shopify-starter]/[graphql-tools]/dist/transforms/transforms.js:5:54

  - Array.reduce

  - transforms.js:4 Object.applySchemaTransforms
    [bva-gatsby-shopify-starter]/[graphql-tools]/dist/transforms/transforms.js:4:23

  - transformSchema.js:18 transformSchema
    [bva-gatsby-shopify-starter]/[graphql-tools]/dist/transforms/transformSchema.js:18:27

  - gatsby-node.js:107 Object.<anonymous>
    [bva-gatsby-shopify-starter]/[gatsby-source-graphql]/gatsby-node.js:107:20

  - Generator.next


success source and transform nodes — 0.467 s
success building schema — 0.185 s
success createPages — 0.000 s
success createPagesStatefully — 0.042 s
success onPreExtractQueries — 0.002 s
success update schema — 0.016 s
error GraphQL Error Encountered 1 error(s):
- Unknown field 'admin' on type 'Query'.

      file: /Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js



success extract queries from components — 0.106 s
success run static queries — 0.001 s
error (node:54059) DeprecationWarning: Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.
success run page queries — 0.008 s — 4/4 538.25 queries/second
success write out page data — 0.006 s
success write out redirect data — 0.001 s
success Build manifest and related icons — 0.113 s
success onPostBootstrap — 0.115 s

info bootstrap finished - 3.354 s

 ERROR  Failed to compile with 1 errors                                                   12:46:54 PM

 error  in ./src/components/collections.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)


 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app

error ✖ 「wdm」:
ERROR in ./src/components/collections.js
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)

 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app
info ℹ 「wdm」: Failed to compile.
 WAIT  Compiling...                                                                       12:46:54 PM

info ℹ 「wdm」: Compiling...
 ERROR  Failed to compile with 1 errors                                                   12:46:54 PM

 error  in ./src/components/collections.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)


 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app

error ✖ 「wdm」:
ERROR in ./src/components/collections.js
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/bva-gatsby-shopify-starter/src/components/collections.js
  54:9  error  Cannot query field "admin" on type "Query"  graphql/template-strings

✖ 1 problem (1 error, 0 warnings)

 @ ./src/pages/index.js 8:0-52 11:107-118
 @ ./.cache/sync-requires.js
 @ ./.cache/app.js
 @ multi event-source-polyfill (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false ./.cache/app
info ℹ 「wdm」: Failed to compile.

 

0 Likes