【问题标题】:How to do a simple GraphQL query in a native Ruby script如何在原生 Ruby 脚本中执行简单的 GraphQL 查询
【发布时间】:2021-01-11 12:10:05
【问题描述】:

我试图弄清楚如何在不使用 gems 的情况下进行简单的 GraphQL 查询。以下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": {} }' 

对应的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));

是否可以在不使用 graphql gem 的情况下在 Ruby 中轻松做到这一点?我只需要像上面的例子那样做简单的查询,所以我希望在一个 Ruby 脚本中很容易做到。

【问题讨论】:

  • 你可以尝试使用 Faraday gem 但也是这样

标签: ruby graphql


【解决方案1】:

您可以使用Ruby core lib Net/HTTP 并像这样构建您的请求:

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)

也见this answer

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 2018-05-08
    • 2019-03-22
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多