HTTParty

HTTParty is a library that allows you to use other API’s and provides responses from them. It’s a good way to connect API’s like Twitter, Facebook to your API. You can also include a .to_json to the response to convert all responses received from the httparty function to be in json

It’s an incredibly useful gem that lets you quickly call other web links and get responses in your application.

When you’re developing with Ruby, it’s pretty inevitable that at some point you come across an HTTP API that doesn’t have a gem available. HTTParty lets you quickly make calls to those APIs

How does it work?

It kind of works like a really-bare bones web browser. You tell it what HTTP method to use and what URL to visit and it’ll go off and grab it for you. It’ll then return the contents of the web response. From there you have to decide what to do with it. You can learn more in the gem’s documentation

response = HTTParty.get('http://myurl.com/path/to/resouce')

puts response.body, response.code, response.message, response.headers.inspect

response = HTTParty.post('http://myurl.com/path/to/resouce')

Some Examples

There are tonnes of examples provided for lots of services and I’d recommend this as a starting point

Worked Example

ScottyLab is an awesome group on campus. They’re a club devoted to helping students learn about and explore interesting topics in technology. And they’ve build some API’s about the campus including courses, directory searches, and campus dining.

None of these API’s have a gem — bah! – which means we’ll need to manually work with them. Thankfully HTTParty makes this a breeze - especially with the excellent documentation ScottyLabs have prepared.

Let’s look at the Directory API - open up the documentation and take a look.

The sample request provided looks like this:

GET https://apis.scottylabs.org/directory/v1/andrewID/odb

And it tells us we need to provide one parameter :id that corresponds to the Andrew ID of the user. We can also see that the responses will be returned in json format and we HTTParty will automatically convert this to a native Ruby Hash so we can use it immediately.

Great. This is lots of info to go on.

In your Gemfile add:

gem 'httparty'

then bundle install

In your app.rb add:

require "sinatra"
require 'sinatra/reloader' if development?
require 'httparty'

require 'twilio-ruby'

enable :sessions

configure :development do
  require 'dotenv'
  Dotenv.load
end


get "/search/:andrew_id" do
  dir = get_directory_info params[:andrew_id]
  
  puts dir
  
  if dir.nil? or dir.empty?
    "Person not found"
  else
    "#{dir["first_name"]} #{dir["last_name"]} matches '#{dir["andrewID"]}'. They are listed as a #{dir["affiliation"]} on the #{dir["campus"]} campus in #{dir["department"].join(" and ")} with the title: #{dir["job_title"]}"
  end
  
end 


def get_directory_info andrew_id
  
  response = HTTParty.get('https://apis.scottylabs.org/directory/v1/andrewID/' + andrew_id )
  
  # returns
  # {"andrewID":"daraghb","first_name":"Daragh","middle_name":"J","last_name":"Byrne",
  # => "preferred_email":"daragh@cmu.edu","campus":"Pittsburgh","department":["Architecture"],
  # => "affiliation":"Faculty","names":["Daragh Byrne","Daragh J Byrne"],
  #   "job_title":"Assistant Teaching Professor","office":"CFA 201"}
  
  # return the response
  response
  
end 


Learn More

  • https://johnnunemaker.com/httparty/
  • https://github.com/jnunemaker/httparty/blob/master/examples/twitter.rb
  • http://blog.teamtreehouse.com/its-time-to-httparty
×

Subscribe

The latest tutorials sent straight to your inbox.