How to Parse an API in Ruby
In our previous lessons on APIs, we were able to get the data we wanted from different APIs, however they all came together, were difficult to read, and weren't very useful. So, in this lesson, we are going to learn to parse the API so that we can get the data we want for further processing.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In our previous lessons on APIs, we were able to get the data we wanted from various APIs, however the data that was returned wasn't very useful. In this guide we are going to learn how to parse the API so that we can get the data we want for further processing.

Let's go back to our Resty API and setup the code like this:

require 'rubygems'
require 'httparty'

class Resty
  include HTTParty
  base_uri 'http://edutechional-resty.herokuapp.com'

  def posts
    self.class.get('/posts.json')
  end
end

resty = Resty.new
puts resty.posts

In this code we're using the HTTParty gem to call the Resty API and we have a posts method that will call the endpoint to retrieve the posts. From there we're simply printing out the response from the API. The resulting response will look something like this:

{"id"=>1, "title"=>"Test Blog Post", "description"=>"Here is the content", "url"=>"http://edutechional-resty.herokuapp.com/posts/1.json"}
{"id"=>2, "title"=>"Testing production SMS sending", "description"=>"Content for post.", "url"=>"http://edutechional-resty.herokuapp.com/posts/2.json"}

To get the individual attributes of this API output, let's create an each block and iterate through it and use the hash syntax to select the title items:

resty = Resty.new
resty_posts = resty.posts

resty_posts.each do |post|
  puts "Title: #{post['title']}"
end

If you execute the code now, you'll have this output:

Title: Test Blog Post
Title: Testing production SMS sending

We can now continue printing more attributes like this:

eductechional_resty.posts.each do |post|
  puts "Title: #{post['title']} | Description: #{post['description']}"
end

If you execute the code, you can see the following output:

Title: Test Blog Post | Description: Here is the content
Title: Testing production SMS sending | Description: Content for post.

So now you know how to successfully parse data coming in from an API. Whenever I find an API that looks intimidating I have found the best approach is to break it down into small, easy to manage chunks. Exactly like how we did in this guide.