vince
vince

Reputation: 2878

How to do a basic GraphQL query to Shopify with Ruby

I'm trying to do a basic GraphQL query to a Shopify store with Sinatra. Could someone help me figure out what I'm doing wrong? I looked at their API to do this:

require 'shopify_api'
require 'sinatra'

class App < Sinatra::Base
  get '/' do
    shop  = 'xxxx.myshopify.com'
    token = 'shpat_xxxxxxxxxxxxxxxxxxxxxx'
    session = ShopifyAPI::Session.new(domain: shop, token: token, api_version: "2021-04")
    ShopifyAPI::Base.activate_session(session)
    
    ShopifyAPI::GraphQL.initialize_clients
    client = ShopifyAPI::GraphQL.client

    SHOP_NAME_QUERY = client.parse <<-'GRAPHQL'
      {
        shop {
          name
        }
      }
    GRAPHQL

    result = client.query(SHOP_NAME_QUERY)
    result.data.shop.name
  end
end

Which gives this error but I don't want to use Rake or Rails. Is it possible to do a GraphQL query to Shopify with Ruby?

ShopifyAPI::GraphQL::InvalidClient at /
Client for API version 2021-04 does not exist because no schema file exists at `shopify_graphql_schemas/2021-04.json`. To dump the schema file, use the `rake shopify_api:graphql:dump` task

Upvotes: 2

Views: 1826

Answers (2)

yaken
yaken

Reputation: 642

As the error states, you need to first dump the schema (see this link: https://github.com/Shopify/shopify_api/blob/v9/docs/graphql.md#dump-the-schema).

Then you create a shopify_graphql_schemas directory in the same root as your ruby script, and put the generated JSON there.

Like stated in the comments, this requires a Rake task, so you need to be using Rails. If your project doesn't use Rails, you need to do a quick workaround.

You create a temporary barebones Rails project, then generate the dump using that project (you can delete the project when you're done with this). It's a bit hacky, but it's the only thing I can see that would work.

Upvotes: 2

Vitalii Isaev
Vitalii Isaev

Reputation: 63

New link to schema dump https://github.com/Shopify/shopify_api/blob/v9/docs/graphql.md#dump-the-schema

You need to use something like this

rake shopify_api:graphql:dump SHOP_DOMAIN="SHOP_NAME.myshopify.com" ACCESS_TOKEN="SHOP_TOKEN" API_VERSION=2022-04

Old one doesn't work anymore

Upvotes: 1

Related Questions