Passing Headers and Query Params in Httparty

Passing headers and query params in HTTparty

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>'

HTTParty headers strange behavior

Hash keys in Ruby can be any object type. For example, they can be strings or they can be symbols. Using a colon (:) in your hash key tells Ruby that you are using a symbol. The only way to use a string (or other object type, like Integer) for your key is to use hash rockets (=>).

When you enter { "Content-Type": "application/json" }, Ruby will convert the string "Content-Type" to the symbol :"Content-Type". You can see this yourself in the console:

{ "Content-Type": "application/json" }
=> { :"Content-Type" => "application/json" }

When you use a hash rocket it does not get converted and remains a string:

{ "Content-Type" => "application/json" }
=> { "Content-Type" => "application/json" }

HTTParty does not work with symbolized keys.

Httparty request query not parsed properly

When you declare the method as def investments(*params), params will contain an array of arguments, and want to pass a hash to your get call. So, either drop the asterisk and simply say def investments(params), or use query: params.first later in the method.

How to pass query params and headers in a single request using grape

Headers are set in about the same way. You pass the headers option to your chosen HTTP method with a hash of the headers you would like to include:

HTTParty.post("http://rubygems.org/api/v1/gems/httparty/owners",
:query => { :email => "alan+thinkvitamin@carsonified.com" },
:headers => { "Authorization" => "THISISMYAPIKEYNOREALLY"})

for more details see Document



Related Topics



Leave a reply



Submit