0

I'm trying to figure out how to do a simple GraphQL query without using gems. The following cURL commands works

curl -X POST "https://gql.example.com/graphql/public" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{ "query": "query { user { id defaultEmail } }", "variables": {} }' 

and the corresponding javascript code is

fetch('https://gql.example.com/graphql/public', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <ACCESS_TOKEN>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: 'query { user { id defaultEmail } }',
    variables: {}
  })
})
.then(r => r.json())
.then(data => console.log(data));

Is it possible to do this easily in Ruby without using the graphql gem? I only need to do simple queries like the examples above so I'm hoping it's easy to do them in a single Ruby script.

vince
  • 2,374
  • 4
  • 23
  • 39

1 Answers1

1

You can use Ruby core lib Net/HTTP and build your requests like so:

require 'net/http'
uri = URI('https://gql.example.com/graphql/public')
params = {'query': 'query { user { id defaultEmail } }', 'variables': {} }
headers = {
    "Authorization'=>'Bearer #{ENV['MY_ACCESS_TOKEN']}", 
    'Content-Type' =>'application/json',
    'Accept'=>'application/json'
}

https = Net::HTTPS.new(uri.host, uri.port)
response = https.post(uri.path, params.to_json, headers)

See this answer as well

lacostenycoder
  • 10,623
  • 4
  • 31
  • 48