无法将ruby变量插入到字符串url中以调用JSON API

时间:2015-07-24 11:33:09

标签: ruby json api httparty

我正在尝试向JSON api发出GET请求,迭代多个JSON对象以提取其ID,然后将它们输入到url中以发出请求。令牌部分工作正常,但我的每个迭代器都有问题,我无法弄清楚。

此api请求的示例GET url是: https://api.hailoapp.com/business/read?id=12345

api应该返回一个有效的响应,但我一直收到400错误,api doc说,这意味着没有id。所以我的代码肯定有问题:

require "json"
require "httparty"

# LOGIN

login_response = HTTParty.post("https://api.hailoapp.com/auth/login",
  {
  :body => { :user => "email@email.com", :password => "password" }.to_json,
  :headers => { "Content-Type" => "text", "Accept" => "application/x-www-form-urlencoded" }
  })

data = login_response.to_hash
api_token = data["api_token"]

# RETRIEVE ACCOUNT

restaurants = JSON.parse File.read('file.json')

input_id = restaurants.each do |r| r["id"]
  retrieve_response = HTTParty.get("https://api.hailoapp.com/business/read?id=#{input_id}",
  {
    :headers => { "Content-Type" => "text", "Accept" => "application/x-www-form-urlencoded", "Authorization" => "token #{api_token}" }
  }) 
  puts retrieve_response.body
  puts retrieve_response.code
  puts retrieve_response.message
end

我在控制台中尝试了这个:restaurants.each { |r| puts r["id"] }但是不知道如何让它与主代码一起使用来访问api。

示例JSON数据:

  {
      "id": "137072",
      "name": "The Brackenbury",
      "phone": "+442087414928",
      "email": "table@brackenburyrestaurant.co.uk",
      "website": "http://brackenburyrestaurant.co.uk/",
      "location": {
          "latitude": 51.4978732,
          "longitude": -0.2313129,
          "address": {
              "line1": "129-131 Brackenbury Road",
              "line2": "Hammersmith",
              "line3": "",
              "postcode": "W6 0BQ",
              "city": "London",
              "country": "UK"
          }
      }
  }

当我使用此代码对api执行类似的POST请求时,它运行正常。

1 个答案:

答案 0 :(得分:1)

此代码......

retrieve_response = HTTParty.get("https://api.hailoapp.com/business/read?id=#{input_id}",
{
  :headers => { "Content-Type" => "text", "Accept" => "application/x-www-form-urlencoded", "Authorization" => "token #{api_token}" }
  }) 

引用一个名为input_id的变量,但实际上整个迭代不是每个实例。

你想要的是......

retrieve_response = HTTParty.get("https://api.hailoapp.com/business/read?id=#{r[:id]}",
{
  :headers => { "Content-Type" => "text", "Accept" => "application/x-www-form-urlencoded", "Authorization" => "token #{api_token}" }
  }) 

使用r r值检索每个迭代实例的响应(该实例称为:id)。

您不需要每个块顶部的独立r[:id],请将其删除。