How to add headers to a httparty call

2019-09-14 14:43发布

问题:

Im trying to add headers to my api call

Heres what i have tried at the moment

api1 = HTTParty.get(URI.encode('apiurllink' + tmname + '&date=' + fromdate + ' TO ' + todate + '', :headers => {"Authorization" => "Bearer apikey"})).parsed_response

This is returning this error

TypeError: no implicit conversion of Hash into String

How do I fix this?

回答1:

Your attempt is raising a TypeError since you are passing the :headers => {"Authorization" => "Bearer apikey"} hash to URI.encode and not HTTParty.get.

api1 = HTTParty.get(URI.encode('apiurllink' + tmname + '&date=' + fromdate + ' TO ' + todate + ''), :headers => {"Authorization" => "Bearer apikey"}).parsed_response

A better way is to use the query option and get HTTParty to construct the query string for you.

response = HTTParty.get('/someuri', 
  query: {
    date: "#{fromdate} TO #{todate}",
    foo: "bar"
  },
  headers: {
    "Authorization" => "Bearer apikey"
  }
)