如何在原生Ruby脚本中执行简单的GraphQL查询
我试图弄清楚如何在不使用gems的情况下执行简单的GraphQL查询。以下如何在原生Ruby脚本中执行简单的GraphQL查询,ruby,graphql,Ruby,Graphql,我试图弄清楚如何在不使用gems的情况下执行简单的GraphQL查询。以下cURL命令有效 curl -X POST "https://gql.example.com/graphql/public" \ -H "Authorization: Bearer <ACCESS_TOKEN>" \ -H "Content-Type: application/json" \ -d '{ "query":
cURL
命令有效
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": {} }'
curl-X POST”https://gql.example.com/graphql/public" \
-H“授权:持票人”\
-H“内容类型:应用程序/json”\
-d'{“查询”:“查询{user{id defaultEmail}}”,“变量”:{}”
相应的javascript代码是
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));
fetch('https://gql.example.com/graphql/public', {
方法:“POST”,
标题:{
“授权”:“持票人”,
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify({
查询:'query{user{id defaultEmail}}',
变量:{}
})
})
.then(r=>r.json())
.then(data=>console.log(data));
在Ruby中,不使用graphql
gem就可以轻松地实现这一点吗?我只需要执行上面示例中的简单查询,因此我希望在单个Ruby脚本中可以轻松地执行这些查询。您可以像这样使用和构建请求:
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)
另请参见您可以尝试使用法拉第宝石,但与此相同