devpreneur
devpreneur

Reputation: 139

HTTPs Request in Ruby with parameters

I'm trying to pull data from a RESTful JSON web service which uses https. They provided a Curl example which works no problem; however, I'm trying to run the query in Ruby and I'm not a Ruby developer.

Any help much appreciated!

cURL example:

curl -G "https://api.example.com/v1/query/" \
     -H "Accept: application/vnd.example.v1+hal+json" \
     -u "$API_KEY:$API_SECRET" \
     -d "app_id=$APP_ID" \
     -d "days=3" \
     -d "metrics=users" \
     -d "dimensions=day"

My attempt in Ruby which is resulting in a HTTPUnauthorized 401:

require 'net/https'
require 'uri'
# prepare request  
  uri = URI.parse("https://api.example.com/v1/query/")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new(uri.request_uri, {
    'Accept' => 'application/vnd.example.v1+hal+json', 
    'api_key' => 'api_secret',
    'app_id' => 'app_id',
    'days' => '3',
    'metrics' => 'users',
    'dimensions' => 'day'})

  response = http.request(request)
  response.body
  response.status
  response["header-here"] # All headers are lowercase

  # Analyze the response
  if response.code != "200"
    puts "Error (status-code: #{response.code})\n#{response.body}"
    print 0
  else
    print 1
  end

** Update ** As per feedback below, I've installed Typhoeus and updated the request. Now I'm getting through. Thanks all!

  request = Typhoeus::Request.new(
    "https://api.example.com/v1/query/",
    userpwd: "key:secret",
    params: { 
      app_id: "appid",
      days: "3",
      metrics: "users",
      dimensions: "day" 
    },
    headers: { 
      Accept: "application/vnd.example.v1+hal+json"
    }
  )

Upvotes: 1

Views: 1351

Answers (2)

khelll
khelll

Reputation: 24000

First you need to realize that:

'Accept' => 'application/vnd.example.v1+hal+json'

is a header, not a parameter.

Also:

$API_KEY:$API_SECRET  

is basic HTTP authentication, not a parameter.

Then, take my advice and go with a better Ruby HTTP client:

Update:

Try the following from IRB:

Typhoeus::Config.verbose = true # this is useful for debugging, remove it once everything is ok.
request = Typhoeus::Request.get(
  "https://api.example.com/v1/query/",
   userpwd: "key:secret",
   params: { 
     app_id: "appid",
     days: "3",
     metrics: "users",
     dimensions: "day" 
   },
   headers: { 
     Accept: "application/vnd.example.v1+hal+json"
   }
 )

Upvotes: 2

Sabuj Hassan
Sabuj Hassan

Reputation: 39365

curl's -u sends the Authorization header. so your 'api_key' => 'api_secret', should be replaced with this one(once again, its http header, not parameter).

"Authorization" => "Basic ".Base64.encode64("api_key:api_secret")
## require "base64"

Upvotes: 1

Related Questions