In this post we will have a look at the Instagram API and how you can use it within Ruby on Rails. Before you get started, you will first need to register an application with Instagram. Go to instagram.com/developers and click manage clients. Click ‘Register New Client’ and make sure you use http://localhost as your redirect URI. I am going to assume that you’re comfortable with Rails basics, such as creating an application, model, view and controller.

Preparing the application

Instagram is kind enough to provide us with a gem that will make development much faster. Create a new application and put the instagram gem in your GemFile with:

gem 'instagram'

The run bundle install.

The next thing we need to do is register our client ID and access token so they can be attached to the query string with every request automatically in true Rails fashion. Create a new file called instagram.rb in config>initializers. Please the following code inside:

 require "instagram"
    Instagram.configure do |config|
    config.client_id = "YOUR CLIENT ID"
    config.access_token = "YOUR ACCESS TOKEN"
 end

To get your access token put the following URL into your browser:

https://api.instagram.com/oauth/authorize/?client_id=[clientID]&redirect_uri=http://localhost&response_type=token

You’ll then be rewarded with your access token.

http://localhost/#access_token=YOUR_ACCESS_TOKEN

If you get an error that says implicit OAuth is disabled, you will need to un-tick ‘Disable implicit OAuth’ in your client settings. Click edit on your client and then click the security tab. Un-tick Disable implicit OAuth and click ‘Update Client’.
Disable-implicity-OAuth

Using the application

You’re now ready to start using the Instagram API in your Rails application. Create a new controller called home with an index view. In config> routed make the index the root of the application with:

root 'home#index'

In your home controller, in the index definition, start creating some variables that can be used on the index of the application. To get popular images make your HomeController look like this:

class HomeController < ApplicationController
  def index
  	@popular = Instagram.media_popular
  end
end

To access Instagram’s endpoints with our popular variable we will loop through the variable and grab the data as we need it. Here is an example of a page that will display 20 of the latest popular Instagram posts and display them a Bootstrap layout.

<h1>Instagram Lookup</h1>
  <% @popular.each do |popular| %>
  <div class="col-sm-12 col-md-4">
    <div class="thumbnail">
      <%= image_tag popular.images.low_resolution.url %>
      <div class="caption">
        <%= popular.user.username %>
      </div>
    </div>
  </div>
<% end %>

You can then practice with all of Instagram’s endpoints that are defined in the documentation found here: https://instagram.com/developer/endpoints/