Downloading Instagram Photos to your Google Drive using Google Apps Script

Sometimes, we would like to download the photos from Instagram to our Google Drive with specific tags of interest and make a backup of those photos.

In this tutorial, I'll tell you how you can use Google Apps Script to fetch photos to your Google Drive.

Register a client first and get the client ID which will be used with Instagram API endpoint.

Once you have got the client Id, Copy and paste below code in a new Google Apps Script File. Change the TAG_NAME to your favorite #tag, also change the CLIENT_ID

function fetchInstagram() {

  

  //Choose your favourite tag

  var TAG_NAME = 'ruralindia';

  

  //Your client Id which you got by registering your client for Instagram API

  var CLIENT_ID = 'abcdef123456789';

  

  //Endpoint url to fetch photos information,

  //note that we have used TAG_NAME and CLIENT_ID with the endpoint URL

  var url = 'https://api.instagram.com/v1/tags/'+TAG_NAME+'/media/recent?client_id='+CLIENT_ID;

  

  //when there is a url to fetch photo details, fetch the details from API

  while(url){

    //let us fetch the details from API. This will give you the details of photos and URL

    var response = UrlFetchApp.fetch(url).getContentText();

    

    //pase the JSON string data to JSON

    var responseObj = JSON.parse(response);    

    

    //get photo data

    var photoData = responseObj.data;

    

    //iterate over this data

    for(var i in photoData){

      var imageUrl = photoData[i].images.standard_resolution.url;

      fetchImageToDrive_(imageUrl);

    }

    

    //Get the url of the next page

    url = responseObj.pagination.next_url;

  }  

}

function fetchImageToDrive_(imageUrl){

  //Fetch image blob

  var imageBlob = UrlFetchApp.fetch(imageUrl).getBlob();

  //Create image file in drive

  var image = DriveApp.createFile(imageBlob);

  //return the URL of the newly created image in drive

  return image.getUrl();

}

Note : If the number of photos are large, the script may time out as it will try to download all the photos in single run. To overcome this, operation can be broken as pages and state of the program can be saved either as script property or as an object in ScriptDb, so that on the next run, script will continue fetching photos where it left.

References : 

Keywrords : Instagram Photos in Google Drive, Backup Instagram photo in Google Drive, Google Apps Script with Instagram API, Google Apps Script UrlFetch to fetch photos/files, Instagram hash tag API and Google Apps Script