Search code examples
rubyhttp

How to get API and manipulate it


With Ruby, no Rails, how can I call an API such as http://api.anapi.com/, and later get a value and check if it is greater than 5?

If it contains an array called anarray which contains hashes, in one of those hashes I want to get to the value of the key key.

Right now I use:

require "net/https"
require "uri"

uri = URI.parse("http://api.cryptocoincharts.info/tradingPair/eth_btc")
http = Net::HTTP.new(uri.host, uri.port)

request = Net::HTTP::Get.new(uri.request_uri)

response = http.request(request)
puts response.body

And I get: #<StringIO:0x2cadb90>

Figured it out:

# http://ruby-doc.org/stdlib-2.0.0/libdoc/open-uri/rdoc/OpenURI.html 
require 'open-uri'
# https://github.com/flori/json
require 'json'
# http://stackoverflow.com/questions/9008847/what-is-difference-between-p-and-pp
require 'pp'

buffer = open('http://api.cryptocoincharts.info/tradingPair/eth_btc').read

# api_key = "FtHwuH8w1RDjQpOr0y0gF3AWm8sRsRzncK3hHh9"

result = JSON.parse(buffer)

puts result["markets"]
# result.each do |user|
#   puts "#{user['id']}\t#{user['name']}\t#{user['email']}"
#   puts "Registered: #{user['created_at']}\n\n"
# end

# my_hash = JSON.parse('{"hello": "goodbye"}')
# puts my_hash["hello"] => "goodbye"

Solution

  • With Net::HTTP:

    require 'net/http'
    uri = URI('http://example.com/index.html?count=10')
    Net::HTTP.get(uri) # => String
    

    Then you can do whatever you want with the data. If for example the API returns JSON, you can parse the String with Ruby's JSON module.