Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

How to do a simple GraphQL query in a native Ruby script

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.

question from:https://stackoverflow.com/questions/65660682/how-to-do-a-simple-graphql-query-in-a-native-ruby-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...