Can Instagram posts be easily retrieved?

February 8, 2018

Edit29 Mar 2018 – In the time between when this article was posted and now, Instagram updated this API. The map() example has been updated to reflect this.

 

Edit22 Apr 2018 – It looks like Instagram has entirely removed the endpoint that this retrieval method depended on. To my knowledge, integrating with Instagram’s new GraphQL API is now the only way to retrieve posts.

 

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.graphql.user.edge_owner_to_timeline_media.edges.map((c) => {
  return ({
    image: c.node.display_url,
    caption: c.node.edge_media_to_caption.edges[0].node.text,
    date: new Date(c.node.taken_at_timestamp * 1000),
    likes: c.node.edge_media_preview_like.count,
    comments: c.node.edge_media_to_comment.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 shortcode 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].shortcode;

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

 

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive