HTTParty: how to make HTTP requests easy
I recently did a technical interview for a local biotech company where I was asked to build a CLI. Since I hadn’t made a simple CLI app in a while, I decided to make a quick practice app before my interview to brush up some rusty skills. Since CLIs are a common starter project for new programmers, I wanted to share one of my favorite tools to make your apps extra cool by tapping into online databases, or APIs.
HTTParty is ruby gem, that you can use to make your CLI apps extra cool. Like any other gem, HTTParty can be installed either by running the command
gem install httpary
in your terminal, or by adding the gem to your gemfile and running bundler to install it. Once you have HTTParty installed make sure to require it in your environment file with all your other gems and then you are ready to jump in.
require ‘httparty’
Now that you have the HTTParty gem up and running, you have access to a new method: HTTParty.get
Notice that this is a class method for the HTTParty class. That means that by installing the gem, you’ve effectively gotten access to a Ruby class called HTTParty, and all its class and instance methods. When you call the class method above and pass in a URL for an API endpoint, and APU key if needed, HTTParty will make a get request to the API and then return the API response to you in the form of a ruby object or hash. For example, in my application I used the get method to fetch data from an API that tells you the names and vessels of all the current astronauts in space (link bellow).
url = ‘http://api.open-notify.org/astros.json'response = HTTParty.get(url)
The response is a ruby hash that looks like this:
{“people”=>[{“craft”=>”ISS”, “name”=>”Mark Vande Hei”},{“craft”=>”ISS”, “name”=>”Oleg Novitskiy”},{“craft”=>”ISS”, “name”=>”Pyotr Dubrov”},{“craft”=>”ISS”, “name”=>”Thomas Pesquet”},{“craft”=>”ISS”, “name”=>”Megan McArthur”},{“craft”=>”ISS”, “name”=>”Shane Kimbrough”},{“craft”=>”ISS”, “name”=>”Akihiko Hoshide”}],“number”=>7,“message”=>”success”}
The hash contains all my astronaut data, plus a success message indicating that my request went through properly. Since HTTParty conveniently reformats the JSON response into a ruby hash, it can now be used however I need in my app, and my users can find out easily what astronauts are in space right now!
Overall HTTParty is a great gem to spiff up you CLI or other ruby apps by accessing data from APIs online and offering it up in a convenient format so that you can use to improve your users’ experience. Go give it a try for yourself!