How to access Instagrams API in 2016

jackLyons Web Development Tags:
0

This is a short post to help front end developers access Instagrams API. Recently I was asked to “plugin” an instagram feed for a client, and after doing some initial research I found that all the tutorials out there were broken and therefore “out of date”.

Gaining access to the API has now become a lot more restrictive in 2016 due to the company’s new regulations. This means that you need to register your app and retrieve a Client ID and an Access token to get anywhere.

You can, of course, purchase an instagram plugin for $10-$20. Alternatively, if you follow this blog post you’ll soon be up and running in no time (and for free!). Here’s a list of things you’ll need for this demo:

And here’s an example of what you will create (NOTE: IT NOW TAKES A FEW SECONDS TO LOAD BECAUSE CODEPEN HAS SOME ISSUES WITH CROSS ORIGIN RESOURCE SHARING):

See the Pen instagram API example by Jack (@JackEdwardLyons) on CodePen.

The number of followers is dynamic (from the time of writing I have 431 followers!), as is the amount of likes per photo. Hover over a photo to  see the cool heart effect that I made. Also, if you click on a photo it will take you to the official Instagram page where you can view everything about the photo. So without further ado, lets dive into this tutorial.

Step 1: Register your app

In order to get up and running you will need to register your app on the Instagram developer page. This is quite straightforward: simply fill in the form presented to you.

You can name your app anything, as well as the company name. Because you won’t be building a commercial product it really doesn’t matter. All we are applying for anyway is a “sandbox licence”, which will give us enough data to create a simple feed of up to 20 photos.

register user id on instagram api

For the website URL, enter a valid URL that is yours. I used my blog’s URL. Same goes for the redirect URI. Enter the same URL as before because this allows Instagram to send you a unique code that will be appended on the end of your URL string. If you’re not exactly sure what a URI is, here’s a simple definition:

“In information technology, a Uniform Resource Identifier (URI) is a string of characters used to identify a resource. Such identification enables interaction with representations of the resource over a network, typically the World Wide Web, using specific protocols.”

Honestly, don’t overthink this form. Just fill in the blanks and click “next”. You will then be presented with your Client ID and be able to manage your profile.

Step 2: Manage your profile

Next thing to do is click “Manage” and then click on “Security”.

This step is important because you will need to disable the “Implicit OAuth” setting in order to make a successful get request on the client side (ie) because we are using jQuery we only have access to the front end and therefore require a special token.

disable oauth

Uncheck the box to disable OAuth then click update and you’re good to go.

Step 3: Authorize your app

The next step requires your permission (or your clients) in order to gain access and authorize the app. Head to the following url and fill in the CLIENT-ID and REDIRECT-URI:

https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token

If everything goes well you will be taken to a page where you’ll be notified that your app is in “sandbox mode” and you’ll be asked to gain access to your basic information. And then, boom you’ve got yourself an Access Token.

Take a look at your websites URL: it will have the token appended to it.

instagram api access token

Step 4: Set your API endpoints

For an in depth look at the various API endpoints head on over to the developer website and see what’s available. If you’re simply after some basic photo information then follow along and I’ll show you how it’s done. With your access token in hand, head to the following URL:

https://api.instagram.com/v1/users/self/media/recent/?access_token=ACCESS_TOKEN

(Note: yes for the cheaters out there you can grab yourself an access token over at pixel union => http://instagram.pixelunion.net/. However you will still need to register your app!).

If all goes correctly then you should get back the JSON and if you’ve installed your JSON viewer as recommended, it should look nice and pretty.


"data": [
    {
      "attribution": null,
      "tags": [
        "olympics2020",
        "bouldergram",
        "rockclimbing",
        "boulderer",
        "climbing_photos_of_instagram",
        "iloveclimbing",
        "travelclimblove",
        "exploremore",
        "rockclimber",
        "climbhard",
        "climbing",
        "clifbar",
        "escalada",
        "adventuresports",
        "climbon",
        "bouldering",
        "rockclimbingphotography",
        "olympicsport",
        "wyoming",
        "climbing_pictures_of_instagram",
        "bouldern",
        "olympics",
        "klettern",
        "olympicathlete",
        "boulderproblem",
        "ilovebouldering",
        "climber"
      ],
      "type": "image",
      "location": null,
      "comments": {
        "count": 6
      },
      "filter": "Normal",
      "created_time": "1470347625",
      "link": "https://www.instagram.com/p/BIs9xY8Dxzj/",
      "likes": {
        "count": 175
      },
      "images": {
        "low_resolution": {
          "url": "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/13741297_1631726967137292_1807852655_n.jpg?ig_cache_key=MTMwOTY5MzI2NjUyNjkzNjI5MQ%3D%3D.2",
          "width": 320,
          "height": 320
        },
        "thumbnail": {
          "url": "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/13741297_1631726967137292_1807852655_n.jpg?ig_cache_key=MTMwOTY5MzI2NjUyNjkzNjI5MQ%3D%3D.2",
          "width": 150,
          "height": 150
        },
        "standard_resolution": {
          "url": "https://scontent.cdninstagram.com/t51.2885-15/e35/13741297_1631726967137292_1807852655_n.jpg?ig_cache_key=MTMwOTY5MzI2NjUyNjkzNjI5MQ%3D%3D.2",
          "width": 640,
          "height": 640
        }
      },
      "users_in_photo": [
 
      ],
      "caption": {
        "created_time": "1470347625",
        "text": "I'm super pumped to hear that sport climbing is now going to be part of the 2020 Olympics!  What an incredible opportunity for the world to see how absolutely epic rock climbing really is!  🏻  🏻 🏻 ------------------------------------------------- #travelclimblove #wyoming #clifbar #rockclimber #climbon #climbing_photos_of_instagram #climbing_pictures_of_instagram #rockclimbingphotography #rockclimber #klettern #escalada #bouldering #exploremore #climbing  #rockclimbing #bouldergram #olympicsport #iloveclimbing #climber #ilovebouldering #boulderproblem #olympicathlete #olympics2020 #olympics #bouldern #adventuresports #climbhard #climbing #boulderer ----------------------------------------------",
        "from": {
          "username": "adventureinmyveins",
          "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11191125_485615798260829_1362168472_a.jpg",
          "id": "1524626894",
          "full_name": "Adventure in my veins"
        },
        "id": "17860312276001348"
      },
      "user_has_liked": true,
      "id": "1309693266526936291_1524626894",
      "user": {
        "username": "adventureinmyveins",
        "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11191125_485615798260829_1362168472_a.jpg",
        "id": "1524626894",
        "full_name": "Adventure in my veins"
      }

In this instance, I am only interested in the “images”. I like the 3×3 grid style pattern on the IG website so to cut things down I’ll only want to retrieve that 9 most recent images.

Step 5: Prepare your GET request

First things first, ensure you have jQuery installed/setup and get your document.ready().


$(document).ready(function() { 
  // code goes here
});

Next you will want to set a variable for the API url you wish to access. This just makes your GET request a bit neater. One thing to note: because I am using CodePen for this DEMO I was unaware that there was some difficulty with API data due to the Cross Origin Resource Sharing restrictions.

A CORS proxy is a service that allows developers (probably you) to access resources from other websites, without having to own that website. Because I don’t own CodePen, duh, I’m just making a simple pen, I need to append “http://crossorigin.me/” to my API url.

You can read more about it on the Cross Origin website.

If you want to display your followers then you will have go through the following endpoint. This will look something like so:

https://api.instagram.com/v1/users/self/?access_token=ACCESS_TOKEN


$(document).ready(function() { 
  var profileUrl = "http://crossorigin.me/https://api.instagram.com/v1/users/self/?access_token=244120591.2f646e9.06a1bfe2c26e49499252236b2be6436b";
  $.getJSON(profileUrl, function(data) {
    var followers = data.data.counts.followed_by;

Then you can append the number anywhere on your page. I have it up the top with my title.


$(".title").append(
      "<h2 class='followers'>\
        <span>" + followers + "</span>\
         <a href='https://www.instagram.com/jacksinstadventure' target='_blank'> followers</a>
      </h2>");

I only want to display the most recent 9 images on my feed. Therefore a simple for loop with a length of 9 will do the trick. I want to access the standard resolution images, which are 640 x 640 pixels by default. But if you wish, you may select the smaller “low_resolution” or “thumbnail” sizes.

And then you can code up the results by creating a list, adding a div, or however you like. Here’s what I did:

I used a for loop to go through the first 9 images. Nothing fancy here…


var apiUrl = "http://crossorigin.me/https://api.instagram.com/v1/users/self/media/recent/?access_token=244120591.2f646e9.06a1bfe2c26e49499252236b2be6436b";
  $.getJSON(apiUrl, function(data) {
    for (var i = 0; i < 9; i++) {
      var instaIMG  = data.data[i].images.standard_resolution.url,
          imgLink   = data.data[i].link,
          userLikes = data.data[i].likes.count;

Now all I have done here is appended each photo as an unordered list item.


$(".instagram").append("<ul>\
  <li class="wrapper">\
   <a href=""+ imgLink + "" target="_blank">\
     <img class="insta-image" src=" + instaIMG + " />\
   </a>
   <div class="img-info">" + userLikes +  "❤"</div>\
  </li>
  </ul>"); 
  } 
});

And that’s about it for the JavaScript! I’m sorry if the code syntax doesn’t look neat. If you really want to use this code for you own project, then feel free to just fork it over at CodePen.

Step 6: Add some HTML and style your images

To create a cool 3 x 3 grid, I created an unordered list that goes from 3 columns, to 2 columns on tablets and down to 1 column on phablets and below.

And here is my CSS *note it may have changed since the time of writing so please refer to the demo for the most recent version.

The cool hover effect was achieved by adding in a class of “wrapper” on the ul as well as a div with the class “img-info”. I positioned the div to the middle of the wrapper and then made it transparent with an opacity of 0. On hover the text appears with a slight transition and the wrapper takes on a dark tint. The tint was achieved by boosting the grayscale and the contrast as well as reducing the brightness. Check out the CSS code below.


* { 
  margin: 0;
  padding: 0; 
}
a {
  color: limegreen;
  text-decoration: none;
}
a:hover {
  color: #0DAF4A;
  cursor: pointer;
}
body {
  background: #1A2980; /* fallback for old browsers */
  background: -webkit-linear-gradient(to left, #1A2980 , #26D0CE); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to left, #1A2980 , #26D0CE); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */     
  box-sizing: border-box;
  font-family: 'Rancho', cursive, tahoma;
  font-size: 20px;
}
.followers {
  margin: 0;
  font-size: 1em;
}
.followers span {
  color: #FF3814;
}
.title {
  color: white;
  font-size: 2.5em;
  margin-top: 2em;
  text-align: center;
  text-shadow: 2px 4px 3px rgba(0,0,0,0.3);
}
.instagram {
  list-style: none;
  margin: 1em auto 0;
  text-align: center;
  width: 90%;
}
.insta-image {
  box-shadow: 2px 2px 2px rgba(0,0,0,0.3);
  margin: 1.5em;
  opacity: 1;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; 
  vertical-align: top; 
  width: 350px;
}
.wrapper {
  display: inline-block;
  margin: 0 auto;
  position: relative;
}
.wrapper .img-info p  {
  color: #fff;
  cursor: pointer;
  font-size: 2em;
  font-weight: bold;
  left: 45%;
  opacity: 0;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  position: absolute;
  top: 35%;
}
.wrapper:hover .img-info p {
  opacity: 1;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
  -webkit-transition: .2s ease;
  transition: .2s ease;
}
.wrapper:hover .insta-image {
  cursor: pointer;
  -webkit-transition: .2s ease;
  transition: .2s ease;
  -webkit-filter: grayscale(100%) brightness(10%) contrast(100%);
}
footer {
  bottom: 2px;  
  height: 40px;  
  margin-top: 40px;  
  position: relative;
  text-align: center;  
  vertical-align: middle; 
  width: 100%;
}
footer img {
  margin: 10px 0;
}
@media screen and (max-width: 430px) {
  .instagram {
    width: 100%;
  }
  .insta-image {
    width: 250px;
  }
  .wrapper .img-info p  {
  left: 41%;
  position: absolute;
  top: 30%;
  }
}

There you go: that’s how you can easily access Instagram’s API. And with that, you’ve got yourself a functional instagram app with some basic data. Style as you wish. If you’d like, please post a comment in the box below with your own version! To see the final demo in action please click here.

If you have any questions, comments or feedback then please leave a note in the comment’s box below!


The Web Developers Bootcamp.

A n00b friendly guide to becoming a pro!

If you’re feeling a bit overwhelmed and a little lost with all these crazy hard Free Code Camp exercises then this course is for you!

While I am oh so grateful for the opportunity to learn through Free Code Camp, I still find that learning to code alone and without proper guidance extremely exhausting. Which is why I’ve started to substitute my education with an incredible online resource called the Web Developers Bootcamp courtesy of Udemy.

This course has helped me brush off the cobwebs, unlearn my self-taught bad habits and gain a solid understanding of the true fundamentals of web development. It has helped me see why it is important to understand these JavaScript problems and how they apply to the real world.

This bootcamp will teach you how built beautiful sites with Bootstrap, add in functionality with JavaScript and write back end code with Node.js all in a series of short, sharp, no BS video modules. I seriously could not recommend it any higher. Check it out and let me know what you think 🙂

The Web Developers Bootcamp
The Web Developer Bootcamp.
The only course you need to learn web development – HTML, CSS, JS, Node, and More!

Sign up to receive up-to-date web tips, tricks and code hacks!