Getting Friendly With Instagram’s API

Using anything from #hashtags to selfies in your rails application.

Kevin McAlear
7 min readMar 2, 2014

Instagram and You.

The power of social media is fantastic and people are using Instagram to do some pretty amazing things. Companies are making real-time mosaics for events and parties, printing out Instagram photos using instaprint. People are creating iPhone cases with their own pictures. Marketers are building platforms to creatively communicate to their customers. Others are finding ways to take Instagram pictures physical.

Developers are still exploring what can be done, making things like a real-time exploration of places through the eyes of Instagram, battling pictures against each other, making your background your feed, enjoying the cats of Instagram, or even trying to help people with an idea I’ve been working on. The point is, now, more than ever, you can do some amazing stuff. Enough talking, lets get into it shall we?

The Breakdown

I will be covering two aspects of this API, the tools I work with and the process of using the API in a program. I’m going to focus on getting you up and running, and assume that the ultimate goal is to be able to feed yourself and use this as a reference once you really start digging into Instagram’s API.

Full disclosure, I’m still learning myself. I am actually in the middle of an intensive web development program and am still solidifying my own skills. With that said, Enjoy!

The Tools

I work in a Ruby environment, using the Rails framework, and hosting everything with Heroku (which uses PostgreSQL) for web apps. This will be the most useful for someone using something similar but not required to just understand Instagram’s API. Lets break down the tools.

HTTParty - Makes http fun again! One-line http magic.

You can query web services, parse the output, and return the response as a Ruby data-structure. (On as side note: if data doesn’t come back in a usable data structure, i.e. one huge string, you can use the JSON ruby gem to convert the string into json. Luckily we don’t need to with this API.)

You can run request like so:

HTTParty.get(‘http://SOMEAPI.com/WHATEVER_ASPECT_YOURE_USING’)

Just so you know, if you don’t want to use HTTParty, there is actually an Instagram Gem you could use instead.

Instagram’s API - Where data comes from. All selfie info is here.

Instagram has a well document, decently straight-forward API. Endpoints are only accessible via https and are located at api.instagram.com. The basics of that API call look like the following:

You can grab the most popular photos at the moment by accessing the following URL with your client ID.

https://api.instagram.com/v1/media/popular?client_id=CLIENT-ID

*On a side note: Make sure you get a client ID right away. It is pretty straight forward but it can be confusing if you don’t know any better. You can get one here and if you want to use Authentication via Instagram you need to get a an Access_Token here.

Active Record - The ORM Rails uses. This will be important later.

Active Record allows us to connect our Database to our Ruby Objects in some pretty powerful ways. I’m telling you this because in further code you will see me call methods on objects that are returning an array of information I’m using in conjunction with the Instagram API. Let’s go through one quick example:

Let’s say I have two tables in my database, users and searches. One user has many searches so I make a user_id column in searches. Then I set up my Active Record Models in Rails. Next the awesome happens. Let’s watch.

So let’s say I want to find the user with an id of one. Now in ruby, I just type:

bob = User.find(1)

(*I’m just saving it to a variable for another part of the example.)

What Active Record actually did was write this:

SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]

It then creates an object in Ruby for me to play with containing everything about this user that was in the database. Pretty cool! Let’s also say that I wanted every search this user made. All I have to do now is this:

bob.searches

Which writes this:

SELECT “searches”.* FROM “searches” WHERE “searches”.”user_id” = $1 [[“user_id”, 1]]

This gives us every search in an array as nice pretty ruby objects!

The Process

Ok, it’s time to actually do this. Lets walk through grabbing a hashtag from a user on a website, dynamically writing an API call, parsing the data, and displaying it back to the user on the web.

A logged in user types in #yolo to look at pictures via a website.

We get the user from the session they are in, using ActiveRecord we then add a new search to our user and our database to use for other stuff, if we desire to later (like seeing our most recent searches or checking out what other users search for, for example). Let’s pretend they fill out a box on a website to put in a hashtag. When they press enter, it will go through this process.

This is what the rails search controller may look like:

def create
@user = User.find(session[:user_id])
@user.searches.new(params[:hashtag])

if @user.save
redirect_to user_path(@user)
else
render(:new)
end
end

We dynamically write an API call request to Instagram.

We take that new search request from the user and feed the hashtag into a method I made to pull back the data. Here are two methods you can check out, one to get the full data about a hashtag and one to just return the total times a hashtag has been used. Check em out!

Here is a method I made to get info on pictures with a hashtag:

def instagram_photos(hashtag)  the_data = HTTParty.get(“https://api.instagram.com/v1/tags/#
{hashtag}/media/recent?client_id=#{INSTAGRAM_CLIENT_ID}”
)

return the_data[“data”]
end

Lastly, a method to get the total count of times a hashtag was used:

def instagram_tag_stat(hashtag)

tag_stats = HTTParty.get(
“https://api.instagram.com/v1/tags/search?q=#
{hashtag}&client_id=#{INSTAGRAM_CLIENT_ID}”
)

return tag_stats[“data”][0][“media_count”]

end

Getting data back in a crazy structure.

Hashes within arrays within hashes…

Let’s start by making an API call to Instagram for some info about the hashtag #yolo and save what we get back to a variable called our_data.

our_data = HTTParty.get(
“https://api.instagram.com/v1/tags/yolo/media/recent?
client_id=#{INSTAGRAM_CLIENT_ID}”
)

The output that we get back is a hash of key, value pairs containing arrays and hashes that contain arrays and hashes. It’s like data inception, very useful data inception actually. Lets break down a bit so we can use it. I’ll quickly go over the skeleton of the data structure you you can explore the juicy information inside.

Accessing this:

our_data[“pagination”]

Gives us:

{
“next_max_tag_id”:”1393732758253",
“deprecation_warning”:”next_max_id and min_id are deprecated
for this endpoint; use min_tag_id and max_tag_id instead”,
“next_max_id”:”1393732758253",
“next_min_id”:”1393732780802",
“min_tag_id”:”1393732780802",
“next_url”:”https://api.instagram.com/v1/tags/yolo/media/recent
?client_id=***INSTAGRAM_CLIENT_ID***&max_tag_id=1393732758253"
}

Accessing this key in our hash will return a hash that allows to you make another API call to get more #yolo photos. Because of the amount of data available Instagram limits how much data you can get per API call to information on the last twenty photos. (#yolo has been been used on 18,290,259 freaking photos at the time of this writing, for example.) So, you will get the key if your #hashtag has been used on more than 20 photos.

Accessing this:

our_data[“meta”]

Gives us:

{
“code”:200
}

The “meta” key is usually short and sweet. It returns meta information (via another hash) on the api call itself. If everything works well you will just get a code number (200 specifically) and if you get any errors they will be inside of meta and help you troubleshoot what is happening.

Accessing this:

our_data[“data”]

Gives us up to twenty of these big hashes containing other hashes and arrays:

[
{
“attribution”:null,
“tags”:[“yolo”],
“location”:null,
“comments”:{ “count”:0, “data”:[] },
“filter”:”Hudson”,
“created_time”:”1393703980",
“link”:”http://instagram.com/p/lAznqkAUz0/”,
“likes”:{ “count”:0, “data”:[] },
“images”:{
“low_resolution”:{
“url”:”http://distilleryimage0.s3.amazonaws.com/
ca4f97e2a17b11e3b8590a1f8b30899c_6.jpg”,
“width”:306,
“height”:306
},
“thumbnail”:{
“url”:”http://distilleryimage0.s3.amazonaws.com/
ca4f97e2a17b11e3b8590a1f8b30899c_5.jpg”,
“width”:150,
“height”:150
},
“standard_resolution”:{
“url”:”http://distilleryimage0.s3.amazonaws.com/
ca4f97e2a17b11e3b8590a1f8b30899c_8.jpg”,
“width”:640,
“height”:640
}
},
“users_in_photo”:[],
“caption”:{
“created_time”:”1393703980",
“text”:”hverdagsbilde 1/5. utfordret av @marthefjeld93 ,sender
videre til @tpt88 💕\n#yolo”,
“from”:{
“username”:”iselinkristensen”,
“profile_picture”:”http://images.ak.instagram.com/profiles/
profile_214645082_75sq_1386628652.jpg”,
“id”:”214645082",
“full_name”:”iselin kristensen”
},
“id”:”666759771872906934"
},
“type”:”image”,
“id”:”666759770983714036_214645082",
“user”:{
“username”:”iselinkristensen”,
“website”:””,
“profile_picture”:”http://images.ak.instagram.com/profiles
/profile_214645082_75sq_1386628652.jpg”,
“full_name”:”iselin kristensen”,
“bio”:””,
“id”:”214645082"
}
}
]

This is where the the actual data we want is. Accessing this key will give us an array of hashes, each hash containing photo information about a specific photo that was tagged with #yolo. From the amount of likes and comments to the filter used, this hash contains nearly anything you could want to know about a specific photo. For example, lets access the first (and only in this case) image’s “standard resolution” photo url so we can use it in our app.

We would just do something like this:

our_data[“data”][0][“images”][“standard_resolution”][“url”]

Which returns the following link we want.

http://distilleryimage0.s3.amazonaws.com/ca4f97e2a17b11e3b8590a1f8b30899c_8.jpg

So, to recap, we accessed the “data” key in the hash which gave us an array of hashes, each hash containing its own photo and all the information we could want about it. We then found the “images” key in the first photo in the array (we got to the first photo with index [0]). Finally, we found the “standard resolution” of the photo and found it’s “url” which gave us a the link we needed.

Note: This is a condensed version of something you may get back for the hashtag #yolo. I’m only showing you info for one picture!

Then it gets restructured and prepared to be viewed.

Here is a peek into what the search controller’s show page could look like. This helps us get everything ready to view and show our user.

def show
@search = Search.find(params[:id])
@tag_count =
instagram_tag_stat(@search.hashtag).to_s.
reverse.gsub(/…(?=.)/,’\&,’).reverse
@pics_info = instagram_photos(@search.hashtag)
end

We feed the data back to the user so he can see as much #yolo as he can handle.

Here we are just iterating through any picture, pulling out the parts we want to write in html, and then serving it back up as a webpage.

<div>
<ul>
<% @pics_info.each do |pic| %>
<li>
<a href=”<%= pic[“link”]%>” target=”_blank”>
<img src=”<%= pic[“images”][“standard_resolution”][“url”] %>”
width=”300px”/>
</a>
<a href=”http://instagram.com/<%= pic[“user”][“username”]%>”
target=”_blank”><p>@<%= pic[“user”][“username”]%></p></a>

<p id=”likes”><%= pic[“likes”][“count”]%> Likes</p>

<p>
<%= truncate(pic[“caption”][“text”], :length => 80) unless
pic[“caption”].nil? %>
</p>

</li>
<% end %>
</ul>
</div>

Code Away, My Friend.

Phew, now that you’ve made it this far it’s time for you to start to play around with your own hashtags and ways to interact with Instagram. Good luck and enjoy!

--

--

Kevin McAlear

I love traveling, technology, wisdom, inventing, ultimate frisbee, leadership, wine, philosophy, humor, culture, differences, relationships, & building systems