How to Work with APIs in Ruby
This is an exciting section as we are going to learn how to work with API calls in Ruby. We'll start out with a basic API example and get into more advanced ways to work with APIs in subsequent guides.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

This is an exciting section as we are going to learn how to work with API calls in Ruby. We'll start out with a basic API example and get into more advanced ways to work with APIs in subsequent guides.

Here, I have an API called Resty that I built for this course. Resty is a short for RESTful interfaces for Routing, and it's a basic API that has posts and makes them available to the API through the json data type, as shown below:

large

Now, we are going to see a basic way to interact with this API.

Create a file called apiexample.rb and open it in the Sublime Tex editor.

There are many requirements for interacting with APIs in Ruby, and in this guide we are going to leverage the httparty RubyGem to handle API communication. If you don't have this gem on your local system, you can install it with the command gem install httparty.

In this file, add the require code to make httparty available to this file. The rest of the code looks like this:

require 'rubygems'
require 'httparty'

class EdutechionalResty
  include HTTParty
  base_uri "http://edutechional-resty.herokuapp.com"

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

In this code, we are creating a class called EdutechionalResty. We start by including the httparty call, and then use a variable that this gem provides called base_uri. As the name suggests, this is the base URI we are going to be using for this application.

Next, we create a method called posts and call an instance of this method. It takes a parameter, which is the endpoint of our API's URL. So, this is all we have to do inside this class.

Now, we have to create an instance of this class and print it out.

api = EdutechionalResty.new
puts api.posts

If you execute this code, you can see that the output will have the values listed from the outside API:

{"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"}

So, this is how you contact an outside API.