Instagram is one of the most popular social networks around. With more than a billion users, it’s safe to say there’s some potential for integrations. We’d like to take a look at what can be achieved using Instagram’s API. We’re going to look into how to use the API, what information we can get from it, and how to use it with Ruby.
How to Sign Up for the Instagram API
On RapidAPI, you’ll find a bunch of different API offerings for Instagram. They all offer different ways of looking at the data (and some more data than others). You should pick up the API that offers what you need, and that adjusts to your budget. For this article, we’re going to be using this one, as it provides everything we’ll need. To use it, you need to get an account at RapidAPI, then subscribe to it.
We’re choosing the free plan, as it’s enough for us for now.
Testing the Instagram API
You have a bunch of options when it comes to playing around with the API to get familiar with it. The easiest one is to test the endpoints straight in the RapidAPI dashboard. There, you can select the endpoint you want to try on the left, look at the parameters it takes in the middle, and the output you can expect on the right. Plus, on the right, you will also find code snippets for dozens of languages, which can help you get started quite easily.
You can of course also use tools like curl or Insomnia to test the API. You’ll just need to configure them correctly so you send your API Key as a header (see the middle section of the dashboard where you’ll find your API Key). For now, take a look at all the endpoints on your left. You can see we can get comments, who liked a post, further info for a post, etc. Notice that most media-related endpoints require the image’s “short-code”. This is the image’s ID you can find the URL. For example, for this image (instagram.com/p/CC6Ehn-Dovk), the short-code is CC6Ehn-Dovk
.
Using the Instagram API with Ruby
We’re going to build a simple Instagram client using Ruby. This tool is going to ask the user for an Instagram URL (like the one above), fetch some data for the image, and present it to the user. For this, we’ll need:
- Ruby
- Sinatra
- Excon
- Bootstrap
To install Ruby (which you might already have installed, depending on your system), follow their official installation instructions. Now, create a new directory and run bundle init
in it, to create a Gemfile
. We’ll use this file to manage our dependencies. If you don’t have bundler installed, install it by running gem install bundler
. Once done, edit the generated file so it looks like this:
source "https://rubygems.org" git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } gem 'sinatra' gem 'sinatra-contrib' gem 'excon'
Now run bundle install
, to install both Sinatra and Excon. Sinatra is going to be our web framework, while Excon our HTTP framework, to consume the API.
1. Build our Sinatra App
Create a new file called app.rb
. This is where our app will live. Start with this:
require 'bundler/setup' Bundler.require(:default) require 'json' require 'sinatra/reloader' if development? get '/' do erb :index, layout: :default end get '/image' do erb :image, layout: :default end
This is a simple skeleton for our app. It’s going to render a form by default (in the /
path), then in the /image
path, we’re going to get the media’s info and render it. We’re using ERB (embedded ruby) to render our templates. Let’s create these files now. Create a folder called views
, and in there, create three files: index.erb
, image.erb
, and default.erb
. This last one is our “layout”, which just means it’s the file that’s going to “surround” our templates, in order to avoid repeating our code. Let’s start with that one:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <title>Instagram</title> </head> <body> <%= yield %> </body> </html>
Notice the yield
call in the body. This is where all our templates are going to render. We’re also using Bootstrap and Font-awesome for easier UI building.
2. Add the Form
Open the index.erb
template and add this:
<div class="container"> <div class="row"> <div class="col-lg-12 mt-5"> <form action="/image" method="get"> <div class="form-row"> <div class="col"> <input type="text" class="form-control" placeholder="Instagram URL" name="url"> </div> <div class="col"> <button class="btn btn-primary" type="submit">Send</button> </div> </div> </form> </div> </div> </div>
Here we’ve created a simple Bootstrap form, where the user can enter an Instagram URL and press send. This will then be sent to our /image
endpoint. You should be able to test this now. Run ruby app.rb
in your terminal, and then, using your browser, head to localhost:4567. You should see the form:
3. Get Instagram Data with the API
In your app.rb
file, modify your /images
endpoint to look more like this:
get '/image' do short_code = params[:url].match(%r{instagram.com/p/([^/]+)})[1] @info = media_info(short_code) @comments = media_comments(short_code) @likers = media_likers(short_code) erb :image, layout: :default end
First, we’re grabbing the short-code from the URL using a simple regular expression. There could be more robust or simpler ways of doing this, but that’s outside the context of this article. We’re then calling some methods to fetch information about this image from the Instagram API. Let’s look at those:
RAPIDAPI_KEY = 'YOUR_API_KEY' def api_request(endpoint, short_code) response = Excon .get( "https://instagram28.p.rapidapi.com/#{endpoint}?short_code=#{short_code}", headers: { 'x-rapidapi-key' => RAPIDAPI_KEY } ) JSON.parse(response.body) end def media_info(short_code) api_request('media_info', short_code) end def media_comments(short_code) api_request('media_comments', short_code) end def media_likers(short_code) api_request('media_likers', short_code) end
Pretty simple and straight to the point. We’re defining a method to call the API, where we can specify which endpoint to call (this to avoid repeating ourselves), and then our previously mentioned methods call this generic one to get the data. Remember to insert your API Key for this to work.
4. Presenting the data to the user
Now that we’re getting data from the API, we need to present it to our user. Edit your image.erb
file:
<div class="container"> <div class="row"> <div class="col-lg-6 mt-5"> <div class="card mb-3"> <img src="<%= @info['data']['shortcode_media']['display_url'] %>" class="card-img-top"> <div class="card-body"> <p class="card-text"> <%= @info['data']['shortcode_media']['edge_media_to_caption']['edges'].first['node']['text'] %> </p> <p class="card-text"> <small class="text-muted"> <i class="fa fa-calendar"></i> <%= Time.at(@info['data']['shortcode_media']['taken_at_timestamp']).strftime('%D %r') %> </small> <small class="text-muted"> <i class="fa fa-user"></i> <%= @info['data']['shortcode_media']['owner']['username'] %> </small> <small class="text-muted"> <i class="fa fa-heart"></i> <%= @info['data']['shortcode_media']['edge_media_preview_like']['count'] %> </small> <small class="text-muted"> <i class="fa fa-comments"></i> <%= @info['data']['shortcode_media']['edge_media_to_comment']['count'] %> </small> </p> </div> </div> </div> </div> </div>
We’re using the data provided in the API (for now, only in the media_info
endpoint) to render a nice preview of the image. You should see something like this:
We’re still missing our comments and a list of who actually liked the post though. Let’s get that from the other API endpoints:
<div class="container"> <div class="row"> <div class="col-lg-6 mt-5"> <div class="card mb-3"> <!-- ... --> <p class="card-text"> <small> <i class="fa fa-heart"></i> <% @likers['data']['shortcode_media']['edge_liked_by']['edges'].sample(5).each do |liker| %> <%= liker['node']['username'] %>, <% end %> and others </small> </p> <% @comments['data']['shortcode_media']['edge_media_to_parent_comment']['edges'].each do |comment| %> <p class="card-text"> <strong><%= comment['node']['owner']['username'] %></strong> <%= comment['node']['text'] %> </p> <% end %> </div> </div> </div> </div> </div>
Take a look at the response data in the RapidAPI dashboard to get an idea of where we’re getting data for each like and comment. Using this above, you should be able to see a list of some likes and some comments:
Conclusion
We hope this article gave you an idea of how to use the Instagram API using Ruby. There are other ways of consuming this API, for example using the snippets provided in the RapidAPI dashboard. There are also more things you can do with this API, like fetching images from a hashtag using the hash_tag_medias
endpoint. You can reuse most of what we’ve done here to test that endpoint and learn more about this API and how to consume it with Ruby.
Also, consider using this API with others on RapidAPI, using the same API Key, to create a more data-rich app.
Leave a Reply