Can't get Events working with JS/Apps Script - always returns invalid Sync Token

I’ve been trying to get the Events endpoint working with Google’s Apps Script, but have been really struggling. I’m able to make all the other calls for getting tasks, creating tasks, getting and creating stories, etc. but this one eludes me!

I originally started with a more complex function that included other features, but for simplicities sake I rewrote it into two more simple functions getSyncToken() and asanaEventCall()

getSyncToken:

This function makes a call without the ‘sync’ parameter, uses muteHttpExceptions to get the full response text, and sets the sync token as a property in Apps Script (just a key/value pair)

var asanaBaseUrl = 'https://app.asana.com/api/1.0'

function getSyncToken() {
  var url = asanaBaseUrl + '/projects/' + asanaProject + '/events'

  var headers = {
    'Authorization': 'Bearer ' + asanaPAT
  }

  var options = {
    'method': 'GET',
    'headers': headers,
    'muteHttpExceptions': true
  }

  var r = UrlFetchApp.fetch(url, options)
  var data = JSON.parse(r.getContentText())


  var newSyncToken = data.sync
  userProps.setProperty('syncToken', newSyncToken)

}

asanaEventCall:

This function uses the properties service to pull the sync token set in the previous call and makes a new call with the sync parameter

function asanaEventCall() {
  var url = asanaBaseUrl + '/projects/' + asanaProject + '/events'
  var syncToken = userProps.getProperty('syncToken')

  var headers = {
    'Authorization': 'Bearer ' + asanaPAT
  }

  var options = {
    'method': 'GET',
    'headers': headers,
    'sync': syncToken,
    'muteHttpExceptions': true
  }
  var r = UrlFetchApp.fetch(url, options)
  var data = JSON.parse(r.getContentText())
  return data
}

However, the second function always returns the same error message:

{sync=[SYNC TOKEN HERE], errors=[{message=Sync token invalid or too old. If you are attempting to keep resources in sync, you must fetch the full dataset for this query now and use the new sync token for the next sync.}]}

I’ve confirmed that the token is being set, retrieved, and sent correctly using the logs.

I’ve done essentially the same workflow as the code above, but manually using the URL, like this:

I feel like I must be missing something very obvious but I just can’t see it, any help would be greatly appreciated!

I ended up getting it working from an answer on StackOverflow - javascript - Asana Events API always returning invalid sync token in Apps Script - Stack Overflow

3 Likes