Infinite Infinite - 3 months ago 15
Ruby Question

Translate Curl to Ruby (New Relic API)

I am extremly new to ruby, but I am playing around with it. Could someone help me translate this curl command to Ruby ?

I have been having a difficult time trying to adapt other ruby examples to fit my needs.

curl -X GET 'https://api.newrelic.com/v2/servers.json' \
-H 'X-Api-Key:12345689' -i \
-G -d 'filter[host]=server1'


Ruby Code:

require 'net/http'

uri = URI.parse('https://api.newrelic.com/v2/servers.json')
request = Net::HTTP::Get.new uri.request_uri

res = Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https') {|http| http.request request}

request.initialize_http_header({'X-Api-Key' => '12345689'})
request.initialize_http_header({'Accept' => 'application/json'})
request.initialize_http_header({'Content-Type' => 'application/json'})
request.set_form_data({"filter[host]" => "server1"})


response = res.request(request)


Error Message:

test.rb:16:in `<main>': undefined method `request' for #<Net::HTTPUnauthorized 401 Unauthorized readbody=true> (NoMethodError)

Answer

Should look something like this:

require 'net/http'

uri = URI('https://api.newrelic.com/v2/servers.json')
uri.query = URI.encode_www_form({ 'filter[host]' => 'server1' })
req = Net::HTTP::Get.new(uri)
req['X-Api-Key'] = '123456789'

http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true
response =  http.request(req)
p response.read_body
Comments