Search code examples
ruby-on-railsrubycurlhttpclientrest-client

make a request using REST_CLIENT, equivalent to a curl request


I am trying to make this curl request using rest_client, and I keep getting it wrong. How can I do it?

curl request: it is working well and returning an access token from yahoo.

curl -u "<consumer_key>:<consumer_secret>" -d "grant_type=authorization_code&code=<code>&redirect_uri=<redirect_uri>" https://api.login.yahoo.com/oauth2/get_token

the rest_client request that I am trying to make work is:

# get token
  yahoo_url = "https://api.login.yahoo.com/oauth2/get_token/"
  response = RestClient::Request.new(
      :method => :get,
      :url => yahoo_url,
      :client_id => $consumer_id,
      :client_secret => $consumer_secret,
      :headers => { :accept => :json,:content_type => :json},
      :params => {'grant_type' => 'authorization_code', 'code' => code, 'redirect_uri' => $yahoo_redirect_url}
  ).execute
  results = JSON.parse(response.to_str)
  puts "RESULTS: #{results}"

or this one:

response = RestClient.get 'https://dj0yJmk9Q1RKU2xclient_id:be49966a23db7_client_secretb@api.login.yahoo.com/oauth2/get_token', {:params => {'grant_type' => 'authorization_code', 'code' => code, 'redirect_uri' => $yahoo_redirect_url}}

Any help or suggestions or even a better too that can work will be appreciated, thanks in advance.


Solution

  • The request must be a HTTP POST instead of a HTTP GET and pass the parameters as in:

    # POST or PUT with a hash sends parameters as a urlencoded form body
    # RestClient.post 'http://example.com/resource', :param1 => 'one'
    

    so:

    response = RestClient.post 'https://dj0yJmk9Q1RKU2xclient_id:be49966a23db7_client_secretb@api.login.yahoo.com/oauth2/get_token', :grant_type => 'authorization_code', :code => code, :redirect_uri => $yahoo_redirect_url