Passing headers and query params in HTTparty

Ruby on-RailsRubyHttp HeadersHttparty

Ruby on-Rails Problem Overview


How to pass query params and headers in post method using HTTparty. I am doing as follows But it throws

query = {:method => "neworder", :nonce => 1404996028, :order_type => "buy", :quantity=>1,:rate=>1}
headers = {:key=> "87819747209090199871234", :sign=> "0a3888ac7f8e411ad73a0a503c55db70a291rsf34bfb9f9a47147d5200882674f717f6ede475669f3453"}

HTTParty.post("https://www.acb.com/api/v2/market/LTC_BTC/", :query => query, :headers => headers )

But it throws the following error. How to handle query string params and headers with HTTparty.

/home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:172:in `capitalize': undefined method `split' for :key:Symbol (NoMethodError)
from /home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:165:in `block in each_capitalized'
from /home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:164:in `each'
from /home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:164:in `each_capitalized'

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Use Strings for your hash keys instead of Symbols.

query = { 
  "method"     => "neworder",
  "nonce"      => 1404996028,
  "order_type" => "buy",
  "quantity"   => 1,
  "rate"       => 1
}
headers = { 
  "key"  => "8781974720909019987",
  "sign" => "0a3888ac7f8e411ad73a0a503c55db70a291bfb9f9a47147d5200882674f717f6ede475669f3453" 
}

HTTParty.post(
  "https://www.acb.com/api/v2/market/LTC_BTC/", 
  :query => query,
  :headers => headers
)

It was probably only the headers that were causing a problem due to the error occurring in net/http/header.rb:172. The important info being undefined method 'split' for :key:Symbol (NoMethodError)

Symbol error in irb:

irb(main):002:0> "Something".split
=> ["Something"]

irb(main):003:0> :Something.split
NoMethodError: undefined method `split' for :Something:Symbol
        from (irb):3
        from /usr/bin/irb:12:in `<main>'

Solution 2 - Ruby on-Rails

It's been a bit old question, but we had the same issue recently, so I try to attach my solutions:

  1. The answer above is working:

    "headers": { "Authorization" => "Bearer #{token}" }

  2. Alternatively, the other solution is:

    headers: { Authorization: "Bearer #{token}" }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - Ruby on-RailsMattView Answer on Stackoverflow
Solution 2 - Ruby on-RailsWinters HuangView Answer on Stackoverflow