Post by Peter Cooper on August 2nd, 2008

HTTParty: Quick Web Service Consumption From Any Ruby Class

httparty.jpg

HTTParty is a new Ruby library by John Nunemaker (of railstips.org fame) that makes it a snap to build classes that can use Web-based APIs and related services. At its simplest, you include the HTTParty module within a class, which gives your class a "get" method that can retrieve data over HTTP. Further directives, however, instruct HTTParty to parse results (XML, JSON, and so on), define base URIs for the requests, and define HTTP authentication information.

HTTParty's simplicity is demonstrated in the most "complex" example John gives in his introduction post - a Representative class that can retrieve information about US Representatives from whoismyrepresentative.com:

require 'rubygems'
require 'httparty'

class Representative
  include HTTParty
  base_uri 'whoismyrepresentative.com'
  default_params :output => 'json'
  format :json

  def self.find_by_zip(zip)
    get('/whoismyrep.php', :query => {:zip => zip})
  end

  def self.get_all_by_name(last_name)
    get('/getall_reps_byname.php', :query => {:lastname => last_name})
  end
end

puts Representative.get_all_by_name('Donnelly').inspect
# {"results"=>[{"district"=>"2", "last"=>"Donnelly", "first"=>"Joe", "state"=>"IN", "party"=>"D"}]}

That code will work for you after a simple gem install httparty. So, join the HTTParty now; it looks pretty fun.

This post is sponsored by KickStart Events — RubyOnRails Training at the EMCC (East Midlands Conference Centre), UK. High-quality hands-on workshops and courses for web application developers. Taught by experienced mentors using live coding sessions, slides and participatory discussion.

[Post to Twitter] Tweet This

2 Responses to “HTTParty: Quick Web Service Consumption From Any Ruby Class”

  1. #1
    John Nunemaker Says:

    Ha! Awesome httparty pic!

  2. #2
    jnstq Says:

    Ah! Nice. I just tried it for a remote login service, works great!