We're live-coding on Twitch! Join us! FREE Webinar: Should I use React or Vue?
Instagram API with Node and Express

Instagram API with Node and Express

In this tutorial we'll be using the instagram API together with node and the node micro-framework express to build a simple photo viewer showing likes count and comment count of a users photo. This should give us a better understand how the API works if we're to work on a project that requires it, Let's get started....

Getting started

File Structure

We won't be using a lot of files for this tutorial, templates are stored in the views folder, styles in the public folder, the rest is pretty much basic.

    - public
    --- css
    ------- styles.css
    - views
    --- pages
    ------- index.ejs
    --- partials
    ------- footer.ejs
    ------- header.ejs
    ------- head.ejs
    - package.json
    - api.js

package.json will hold our application and package information, api.js is where all the core work will be done, let's take a look at our package.json file :

Node Setup

ejs will be used as our template engine of choice, you could also use pug or any other template you're familiar with. express will be used to handle our routing, redirect, etc... instagram-node is just an npm package that helps us work with the API with much ease, not compulsory but very useful, documentation can be found here.

{
  "name": "instagram-api",
  "main": "api.js",
  "dependencies": {
    "ejs": "^2.3.1",
    "express": "^4.12.1",
    "instagram-node": "^0.5.6"
  }
}

Let's go ahead and install our dependencies, run this piece of code in your terminal :

$ npm install

Setting up our Template

These are our partials, this helps us reduce redundancy, so we could just add these files across our site where we need them rather than repeatedly writing them

// views/partials/head.ejs
<meta charset="UTF-8">
<title>Instagrm API</title>

<!-- CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.2/cosmo/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
// views/partials/header.ejs
<nav class="navbar navbar-inverse">
<div class="container-fluid">
    <div class="navbar-header">
        <a href="/" class="navbar-brand">
            <span class="glyphicon glyphicon-picture"></span>
            Instagram Photos
        </a>
    </div>
</div>
</nav>
//  views/partials/footer.ejs
<p class="text-center text-muted">
    Copyright © 2017 Photonic
</p>

Getting Credentials

We'll need some form of authorization to be able to use the API, so the first step is to go to the Instagram developer site and click on log in at the right hand corner.

Then after you've logged in with your instagram details, click on manage clients at the top right corner also, you'll be redirected to another page.

In the image below i already have a registered client, but in your case, you''ll have to register a new client, click on the Register a New Client button.

Fill in the necessary details required, but take note of what we fill into valid redirect URI's box, it'll come in handy when we're trying to get our access token

If you successfully completed the previous step, a new client will be created as shown below, click on the manage button, we'll be redirected to a new page where we'll be able to get our client_id and client_secret key.

Copy the client_id and client_secret, this is what we'll use in our application to get our access_token

Setting up our application

A basic setup of our application

//  api.js
var express = require('express');
var app = express();
var ig = require('instagram-node').instagram();

//location of our static files(css,js,etc..)
app.use(express.static(__dirname + '/public'));

//set the view engine to use ejs
app.set('view engine', 'ejs');

ig.use({
    client_id: 'YOUR CLIENT ID KEY',
    client_secret: 'YOUR CLIENT SECRET KEY'
});

//the redirect uri we set when registering our application
var redirectUri = 'http://localhost:8080/handleAuth';

...

Note the ig.use() method , we'll pass in our client_id and client_secret key gotten from instagram, for more information about this method visit the docs

Getting the access token

There are two steps to getting the access token :

1. Directing to the instagram authorization url :

The ig.get_authorizaton_url method helps us construct this url using the client_id we provided to ig.use(). The redirectUri parameter is where our app will be redirected to after the instagram authorization, and the scope is an optional parameter which determines what content we would have access to, more info about scopes here. The url constructed by the ig.get_authorization_url is in this format https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code Note : A query code is attached to the redirect URI we provided

...

app.get('/authorize', function(req, res){
    // set the scope of our application to be able to access likes and public content
    res.redirect(ig.get_authorization_url(redirectUri, { scope : ['public_content','likes']}) );
});

...

2. Request the Access token :

Now we need to exchange the query code we have received in the previous step for an access token. In order to make this exchange, we simply have to POST this code along with some app identification parameters to our access token endpoint. The ig.authorize_user method helps us construct this url to get our access token, all we need are three required parameters, the query code already attached to our route, the redirect URI we've been using and a callback function which will contain our access token and some user details in a neatly packaged JSON format. After we get this access token, we'll redirect to the '/' route.

...

app.get('/handleAuth', function(req, res){
    //retrieves the code that was passed along as a query to the '/handleAuth' route and uses this code to construct an access token
    ig.authorize_user(req.query.code, redirectUri, function(err, result){
        if(err) res.send( err );
    // store this access_token in a global variable called accessToken
        accessToken = result.access_token;
    // After getting the access_token redirect to the '/' route 
        res.redirect('/');
    });
})

...

Getting photos

Now we have all we need in order to use the API to get some user information, we'll pass our received access token to the ig.use method. We'll use the ig.user_media_recent method provided by the instagram node package to get the recent user photos. The first parameter of this function requires our user id, this user id is the first part of the access token eg For an access token of 493994571.5ev83n9.c340e9c1e5b0hf6sbd7gj47rnf7dn49m , 493994571 is the user id. We''ll also need a callback function, the response is stored in the result paramter of our callback function. We'll pass this to our view template.

...

app.get('/', function(req, res){
   // create a new instance of the use method which contains the access token gotten
    ig.use({
     access_token : accessToken
    });

    ig.user_media_recent('access_token.split('.')[0]', function(err, result, pagination, remaining, limit) {
        if(err) res.json(err);
     // pass the json file gotten to our ejs template
        res.render('pages/index', { instagram : result });
    });
});

app.listen(8080);

Displaying the results

When we've gotten our results in JSON format, we'll run a loop through each of them and display them together with the likes count and comments count. You can also try to view the JSON object if you need to access other specific details. Note : We are using the variable that we passed to our view, this variable contains the result in JSON format.

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

    <header>
        <% include ../partials/header %>
    </header>

    <main>
        <div class="row">
        <% instagram.forEach(function(insta) { %>
        <div class="instagram-pic col-sm-3">

            <a href="<%= insta.link %>" target="_blank">
                <img src="<%= insta.images.standard_resolution.url %>" class="img-responsive">
            </a>

            <div class="instagram-bar">
                <div class="likes">
                    <span class="glyphicon glyphicon-heart"></span> <%= insta.likes.count %>
                </div>

                <div class="comments">
                    <span class="glyphicon glyphicon-comment"></span> <%= insta.comments.count %>
                </div>
            </div>

        </div>
        <% }); %>
        </div>
    </main>

    <footer>
        <% include ../partials/footer %>
    </footer>

</body>
</html>

Outcome

This is what our final result should look like

Conclusion

We've been able to use the instagram API to build a simple photo viewer, this should give us a proper introduction into how the API works, you could extend the functionalities of this app to do much much more eg show comments, like posts, etc... Checkout the instagram API documentation to learn more. Note : You won't be able to get information of other users because you're in 'sandbox' mode, this feature is only available in 'live' mode, your app will have to get approved by instagram for it to be in 'live' mode.

Like this article? Follow @Devgson_ on Twitter