Make Yahoo! Web Service REST calls with Ruby

This HOWTO describes how to perform GET and POST requests using Net::HTTP and Net::HTTPS, both part of the Ruby standard library.

Simple GET requests

The simplest way of retrieving data from a URL is to use the get_response method:

require 'net/http'

url = ''
resp = Net::HTTP.get_response(URI.parse(url)) # get_response takes an URI object

data = resp.body

The URL should not contain illegeal characters. Hence the query parameter which, in many cases, will be accepted as user input, needs to be encoded using the URI.encode method.

url = "{URI.encode("premshree pillai")}&results=1"

The above code would work fine, but you need a way to handle excpetions—in case of 404 or 500 errors:

require 'net/http'

   data = Net::HTTP.get_response(URI.parse(url)).body
   print "Connection error."

Simple POST requests

Some APIs require you to make POST requests. Net::HTTP provides a post method for this:

require 'net/http'

url = URI.parse('')
appid = 'YahooDemo'

context = 'Italian sculptors and painters of the renaissance favored
the Virgin Mary for inspiration'
query = 'madonna'

post_args = {
   'appid' => appid,
   'context' => context,
   'query' => query

resp, data = Net::HTTP.post_form(url, post_args)

Authenticated requests

The API requires you to make authenticated requests, passing your username and password using HTTP authentication. Net::HTTP provides a mechanism for doing this.

require 'net/https'
http ='', 443)
http.use_ssl = true
http.start do |http|
   req ='/v1/tags/get')

   # we make an HTTP basic auth by passing the
   # username and password
   req.basic_auth 'username', 'password'

   resp, data = http.request(req)

Further reading

Yahoo Forum Discussions