2

i can get response from API using curl like this:

curl -X GET https://myapi.com/... -H "client_id: my_id" -H "client_secret: my_secret" 

but when i send requests with HTTParty:

response = HTTParty.get(url, headers: {"client_id" => "my_id", "client_secret" => "my_secret"})

the result is:

#<HTTParty::Response:0x55e5db898160 parsed_response="Unable to retrieve client_id from message", 
@response=#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>, @headers={"cache-control"=>["no-cache"], "pragma"=>["no-cache"], "content-length"=>["41"], "content-type"=>["text/plain"], "expires"=>["-1"], "server"=>["Microsoft-IIS/8.5"], "strict-transport-security"=>["max-age=31536000; includeSubdomains;"], "x-aspnet-version"=>["4.0.30319"], "x-powered-by"=>["ASP.NET"], "access-control-allow-origin"=>["*"], "access-control-allow-credentials"=>["true"], "access-control-allow-headers"=>["*"], "access-control-allow-methods"=>["GET, POST, PUT, DELETE, OPTIONS"], "date"=>["Wed, 13 Apr 2022 08:56:56 GMT"], "connection"=>["close"]}>

and output from response.request is:

#<HTTParty::Request:0x000055e5db897120 @changed_hosts=false, @credentials_sent=false, @http_method=Net::HTTP::Get, 
@options={:limit=>5, :assume_utf16_is_big_endian=>true, :default_params=>{}, :follow_redirects=>true, :parser=>HTTParty::Parser, :uri_adapter=>URI, :connection_adapter=>HTTParty::ConnectionAdapter, :headers=>{"client_id"=>"my_id", "client_secret"=>"my_secret"}}, 
@path=#<URI::HTTP http://my_api.com/...>, @last_uri=#<URI::HTTP http://my_api.com/...>, @raw_request=#<Net::HTTP::Get GET>, @last_response=#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>>

my opinion is, the headers goes in @options parameter instead of @headers, so request can't find my client_id. Does anyone know how can i fix this?

  • You're calling it correctly. The signature of the method is `#get(path, options = {}, &block) ⇒ Object` and `headers` is supposed to be passed through the `options` parameter. [See the docs](https://www.rubydoc.info/github/jnunemaker/httparty/HTTParty/ClassMethods). Not sure what you're trying to say with `@options` and `@headers` as you're using HTTParty proceedurally instead of the OOP way. – max Apr 13 '22 at 11:58
  • If I had to venture a guess to why this is not working its that you're not passing the id and client secret that you think you are. Also the lack of content-type headers irks me. – max Apr 13 '22 at 12:00
  • 1
    I tested it with javascript, curl and online api testing tool, Api and headers working fine. i workaround this by using `response = eval(`curl command`)` in ruby. But still no idea about why HTTParty and other gems giving unauthorized error. – darkinSchyde Apr 15 '22 at 09:20

1 Answers1

-1

Do not use eval on an API response. Its extremely insecure. Use JSON.parse.

max
  • 96,212
  • 14
  • 104
  • 165