HTTParty headers strange behavior

Xero

Context :

I'm using HTTParty to do a POST request on an API that accept application/json

My body is something like that (as a hash)

{:contact_id =>"12345679", 
 :items=> [
      {:contact_id=>"123456789", :quantity=>"1", :price=>"0"},
      {:contact_id=>"112315475", :quantity=>"2", :price=>"2"}
]}

Issue :

When I write the following code, this is working :

HTTParty.post('https://some-url', body: content.to_json, headers: { "Content-Type" => "application/json" } )

But when change only the => symbol in headers, to : symbol, this is not working (the API respond that some parameters are missing)

HTTParty.post('https://some-url', body: content.to_json, headers: { "Content-Type": "application/json" } )

Question :

Why changing "Content-Type" => "application/json" to "Content-Type": "application/json" lead to errors ?

I think this is something with Ruby hash that I don't understand.

Edit :

I think my question is not a duplicate of Why is this string key in a hash converted to a symbol?

It's important for HTTParty consumers, to know that HTTParty do not accept symbols for headers but only strings.

For more information, see Content-Type Does not send when I try to use a new Hash syntax on header and Passing headers and query params in HTTparty

Thank you @anothermh

anothermh

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related