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.
Installation is pretty simple, issue the following command as a root user:
That's it, HTTParty is installed.
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:
That looked pretty simple, HTTParty can also handle HTTP Basic Auth, let's see how:
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:
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 10:02.|