Can Instagram posts be easily retrieved?

Mike Wang

Displaying Instagram posts on your website can be unexpectedly confusing. Most developers’ first thought is to use the Instagram API to pull in content. Unfortunately, Instagram’s API requires clients to use the decidedly complex OAuth 2.0 protocol. Even worse, the API is being deprecated in July 2018 (per this announcement), so any work done with the API now will need to be redone in six months anyway.

Fortunately, if all you want to do is display a few instas from a single user on your site, there’s an easier way.

GET requests to URLs of the form https://www.instagram.com/${username}/?__a=1 will return a JSON object containing the 12 latest posts by the user ${username}. For example, https://www.instagram.com/mikevonwang/?__a=1 returns the following JSON:

screenshot of long JSON objectThis goes on for 9 more kilobytes.

After a quick JSON.parse(), we now have an Object we can comb through to get the data we want. Let’s call this Object data. If we just want a neat little Array of images, we can do a map():

const posts = data.user.media.nodes.map((c) => {
  return ({
    image: c.display_src,
    caption: c.caption,
    date: new Date(c.date * 1000),
    likes: c.likes.count,
    comments: c.comments.count,
  });
});

There! posts now contains 12 Objects, each containing information about an Instagram post:

screenshot of console.log of posts variable

From here, we can create an <img/> element for each post and style them to our heart’s content.

We can also make each image link back to the original post on Instagram. In the original JSON, each image Object also comes with a code property set to a string like 'BYgmA03Abn7'. Add that property to your mapping function, assemble an href like this:

const href = "https://www.instagram.com/p/" + posts[0].code;

wrap each <img/> element inside an <a/>, add the href, and you’re done!

 

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *