Go4Expert (http://www.go4expert.com/)
-   Ruby on Rails (http://www.go4expert.com/articles/ruby/)
-   -   Access Web Services & Remote URLs with Ruby's HTTParty (http://www.go4expert.com/articles/access-web-services-remote-urls-rubys-t29624/)

pradeep 22Apr2013 19:11

Access Web Services & Remote URLs with Ruby's HTTParty
As programmers most of us today are writing programs/scripts that consume data from web services or APIs, like the Facebook Graph API, etc. Writing your own subroutines from open socket and making request and the likes are time consuming and are not worth putting effort on for all projects, so Ruby has a gem called HTTParty which will help you concentrate on the business logic instead of mundane HTTP request tasks.

HTTParty is a very neat gem, it combined with the power of Ruby creates a lucid and free flowing code. HTTParty can automatically parse JSON/XML type responses on the basis of the Content-Type header. In this article we'll look at the installation of the HTTParty gem and basic usage to get you started.

Installing The HTTParty Gem

Installation is pretty simple, issue the following command as a root user:


$ gem install httparty

That's it, HTTParty is installed.

Using HTTParty To Fetch Remote URLs

Let's look at a very basic example of fetching Google's homepage and printing the content and the HTTP response code, follow the code below:

Code: Ruby

require 'rubygems'
require 'httparty'

response = HTTParty.get('http://www.google.com')

print response.code, response.body

That looked pretty simple, HTTParty can also handle HTTP Basic Auth, let's see how:

Code: Ruby

require 'rubygems'
require 'httparty'

response = HTTParty.get('http://www.go4expert.com/admin',{:basic_auth => {:username => 'pradeep', :password => 'test'}})

print response.code, response.body

Next is a demo Ruby class I have written which gets Facebook info using the Graph API, you'll need to pass a valid access token for it to work, you can get one from at https://developers.facebook.com/tools/explorer
I have commented the code as required, so that you find it easier to follow:

Code: Ruby

require 'rubygems'
require 'httparty'

## define class
class Facebook
  ## load and inherit HTTParty class
  include HTTParty
  ## set the default base URI
  base_uri 'https://graph.facebook.com'
  ## set the format to JSON, so that HTTParty will automatically decode it
  format :json

  ## constructor
  def initialize(access_token)
    @access_token = access_token

  def get_info
    self.class.get('/me',:query => { :access_token => @access_token })   

## create an instance of the Facebook class
fb = Facebook.new(<your-access-token>);

## call the method
r = fb.get_info()

print r.body

Vinus26 23Apr2013 15:20

Re: Access Web Services & Remote URLs with Ruby's HTTParty
Great information thanks for sharing this information.

All times are GMT +5.5. The time now is 22:45.