Before


After


We'll be using the new Instagram API within the Facebook Marketing API reference. Read all about the Instagram Graph API here.

The goal of this tutorial is to extract the number of comments, likes, media, follows, followers and engagement from your Instagram profile

To get started, make a copy of the above Google Sheet and open your script editor by going to "Tools" -> "Script editor".

Step 1 - Create a Facebook access token

To get an access token, you first have the create a Facebook app. You can do this right here.

From there on head over to the Graph API explorer to generate an access token. Make sure to give your token the following permissions:
  • instagram_basic
  • pages_show_lists

Step 2 - Increase the lifespan of the access token

Standard access tokens are only valid for around 30 minutes, which isn't too handy if you want to use this script many times.

Luckily you can quite easily extend that duration via the access token debugger.  Open the debugger, paste in your access token, and extend its expiry date. It should now last at least a few months, but it might still be good to set up a reminder somewhere.

Step 3 - Request account IDs

After you've copied your long-lived access token into the sheet we can run the script. Firstly, we need to figure out to which account you've got access. We do that with the /me/accounts request.

 //define in what sheet to import
 var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  
 // Permissons required: pages_show_list, instagram_basic
 // get access token from the sheet 
 var accessToken = sheet.getRange(2,2).getValue(); 
  
 // get accounts from API
 var apiUrlGetAccounts = 'https://graph.facebook.com/v7.0/me/accounts?access_token=' + accessToken; 
 var responseApiGetAccounts = UrlFetchApp.fetch(apiUrlGetAccounts);
 var result = JSON.parse(responseApiGetAccounts.getContentText());
  
 // define arrays to import into sheet
 var name = [];
 var id = [];
 var arrayLength = result.data.length;
  
 // push results into the arrays to get accounts 
 for (var i=0; i<arrayLength; i++){
   name.push([result.data[i].name]); 
   id.push([result.data[i].id]); 
 };
  
 // remove prior data from the sheet in range A5:D 
 var sheetRange = sheet.getRange("A8:B").clear();
  
 // import account IDs
 sheet.getRange(8, 1, arrayLength, 1).setValues(name);
 sheet.getRange(8, 2, arrayLength, 1).setValues(id)
  
}

Step 4 - Fetch posts from the Instagram business account

Once we have your account ID, we can find the Instagram business account ID and fetch the associated posts. However, this will only work if you've already linked your Facebook and Instagram accounts together.

//Define in what sheet to import
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  
// Permissons required: pages_show_list, instagram_basic
// Get input values from the sheet 
var accessToken = sheet.getRange(2,2).getValue(); 
  
//Get business account profile
var PageID = sheet.getRange(5,1).getValue();
var apiUrl = 'https://graph.facebook.com/v7.0/'+ PageID +'?fields=instagram_business_account&access_token=' + accessToken; 
var responseApiGetBusinessAccount = UrlFetchApp.fetch(apiUrl);
var resultBusinessAccount = JSON.parse(responseApiGetBusinessAccount.getContentText());
  
//Define BusinessID
var BusinessID = resultBusinessAccount.instagram_business_account.id;
  
//Get all media with a limit of 1000 post
var apiUrl = 'https://graph.facebook.com/v7.0/'+ BusinessID +'/media?limit=1000&access_token=' + accessToken; 
var responseApiGetMedia = UrlFetchApp.fetch(apiUrl);
var mediaResult = JSON.parse(responseApiGetMedia.getContentText());

Step 5 - Calculate total comments and likes

Now that we have the posts, we just have to fetch the comments and likes per post in order to calculate the totals.

//Define empty array to push media to
var media = [];
   arrayLength = mediaResult.data.length;
  
//Push results into the array 
for (var i=0; i<arrayLength; i++){
  media.push([mediaResult.data[i].id]); 
};
      
//Define empty array to insert media details
var commentsCount = 0;
var like_count = 0;
    
//Loop through all posts and get details  
for (var i=0; i<media.length; i++){
      
//Define post
var MediaID = media[i];   
      
//Get details for that post
var apiUrl = 'https://graph.facebook.com/v7.0/'+ MediaID +'?fields=comments_count,like_count&access_token=' + accessToken; 
var responseApiComments = UrlFetchApp.fetch(apiUrl);
var result = JSON.parse(responseApiComments.getContentText());
      
//Push post details to the array
commentsCount = commentsCount + result.comments_count;
like_count = like_count + result.like_count; 
}

Step 6 - Calculate total media, followers and follows

Using a very similar fetch to the business ID we can get the total numbers of followers, follows and media in one go. Nice and easy!

// get all instagram business account details
var apiUrl = 'https://graph.facebook.com/v7.0/'+ BusinessID +'?fields=media_count,follows_count,followers_count,username&access_token=' + accessToken; 
var responseApiGetMedia = UrlFetchApp.fetch(apiUrl);
var BusinessIDResult = JSON.parse(responseApiGetMedia.getContentText());
  
// define empty array to push media to
var media_count = BusinessIDResult.media_count;
var follows_count = BusinessIDResult.follows_count;
var followers_count = BusinessIDResult.followers_count;

Step 7 - Calculate engagement

Since we have all the metrics by now, it has become quite easy to come up with a formula for the profile's overall engagement. I've chosen to use the following:

var engagement = (commentsCount + like_count) / followers_count;


Step 8 - Insert metrics into the sheet

The last step of this tutorial is to insert the metrics into the cells of our choice. 

sheet.getRange(2, 5,1,1).setValue(commentsCount);
sheet.getRange(3, 5,1,1).setValue(like_count);
sheet.getRange(4, 5,1,1).setValue(media_count);
sheet.getRange(5, 5,1,1).setValue(follows_count);
sheet.getRange(6, 5,1,1).setValue(followers_count);
sheet.getRange(7, 5,1,1).setValue(engagement);

If you now hit "run" it should insert the latest statistics of your account. To take this further you can follow one of my other tutorials showcasing how to auto-update and store past values on a daily basis.


Let me know if this was useful & let's connect on     or