- Read Tutorial
- Watch Guide Video
In the last lesson: Introduction to APIs in Ruby, we built a class to call an outside API. In this lesson, we are going to walk through some shortcuts for using the HTTParty RubyGem and work with the StackOverflow API.
Let's start by creating a variable called response
, and pass a URL to the get
method of HTTParty.
require 'rubygems' require 'httparty' response = HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow')
Now, we'll see the different features provided by the built-in HTTParty
methods.
First is the body
method that can be called with the code:
response.body
This will give the following output.
This is the body of all the items available in the stackexchange
api that we accessed through the HTTParty get
method. You can see the different attributes in every page. You can even copy one of the URL's from the body and check it on the browser.
Now, instead of body
, let's see what happens when you use a method called code
.
puts response.code
If you execute this code, you'll see that it returns a status code of 200
, which means it's working fine.
This method is mainly used to test if a particular API is working so that you take actions based on on the status value. For example, if the output returns a value of 404
, it means the API does not exist at all and 500
means there is a problem with the API's server.
Next, let's try another method called message
. The code is:
puts response.message
After running this you'll see that the output is OK
.
Next we'll take a look at the API headers with the code
puts response.headers.inspect
The output will have all the headers.
{"cache-control"=>["private"], "content-type"=>["application/json; charset=utf-8"], "access-control-allow-origin"=>["*"], "access-control-allow-methods"=>["GET, POST"], "access-control-allow-credentials"=>["false"], "x-content-type-options"=>["nosniff"], "date"=>["Wed, 07 Sep 2016 03:58:01 GMT"], "connection"=>["close"], "content-length"=>["4997"]}
So, you can query an entire API and inspect it thoroughly with a mere few lines of code, which showcases the power and simplicity of the HTTParty gem.