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 = 'http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=1' 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 = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=#{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' begin data = Net::HTTP.get_response(URI.parse(url)).body rescue print "Connection error." end
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('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction')
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 del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. Net::HTTP provides a mechanism for doing this.
require 'net/https'
http = Net::HTTP.new('api.del.icio.us', 443)
http.use_ssl = true
http.start do |http|
req = Net::HTTP::Get.new('/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)
end
Further reading
Ready to get started?
By applying for an Application ID for this service, you hereby agree to the Terms of Use
Yahoo! Groups Discussions
view all
CASUAL BROWSING MAKES U EARNING
Thu, 04 Sep 2008
Rboss RubyGem for interacting with Yahoo Boss Search
Fri, 22 Aug 2008
Using the Yahoo Address Book APIs with ROR - a step by step tutorial
Tue, 08 Jul 2008
Re: Hi, I coded a Ruby library for Yahoo LifeType API.
Thu, 17 Apr 2008


Send Your Suggestions