Fetching data from the web
So far we've built websites – now let's turn the tables and fetch some. Ruby's standard library ships net/http for that: you build a URI object from an address and send a request. Let's fetch the official Ruby website:
require "net/http"
response = Net::HTTP.get_response(URI("https://www.ruby-lang.org/en/"))
response.codeget_response returns a response object: code is the status code (as a String – a famous little quirk of net/http!), and body holds the whole page as HTML text:
response.body[0, 160]Modern services usually deliver data as JSON – perfect for processing. You already know the rubygems.org API from the gems lesson; let's ask it how often rack has been downloaded:
require "json"
data = JSON.parse(Net::HTTP.get(URI("https://rubygems.org/api/v1/gems/rack.json")))
data["downloads"]The GitHub API answers with JSON too – for example with the stars of Ruby itself:
repo = JSON.parse(Net::HTTP.get(URI("https://api.github.com/repos/ruby/ruby")))
repo["stargazers_count"]Honest footnote: in the browser Ruby sits in a sandbox and may not talk to arbitrary servers. This site therefore provides a little bridge – reachable are www.ruby-lang.org, rubygems.org and api.github.com; other addresses raise a SocketError. On your own computer net/http works with any URL.
sinatra: parse https://rubygems.org/api/v1/gems/sinatra.json into a variable info and make the cell yield the number of downloads (info["downloads"]).require "net/http"
require "json"
# info = JSON.parse(Net::HTTP.get(URI("...")))
# info["downloads"]