1

I'm attempting to query items out of the Todoist API from Google Apps Script, mimicking a curl POST.

I originally tried to make OAuth2 work, but tokens were not persistent, and I instead opted for the API's method of using individual API tokens to exchange for a valid token.

Using App Script's UrlFetchApp class, I'm attempting to construct at POST request for Todoist's API to retrieve task items, and my getTodoistToken() function is indeed retrieving a valid token response, but the POST command is issuing the following 403:

"error_tag":"AUTH_CSRF_ERROR","error_code":0,"http_code":403,"error_extra":{"access_type":"web_session"},"error":"AUTH_CSRF_ERROR"}

Can anyone recommend a solution? Thanks so much, code below:

function getTodoistToken() {
  var url = "https://todoist.com/api/access_tokens/migrate_personal_token";
  var data = {
    "client_id": "[my unique client_id]",
    "client_secret": "[my unique client_secret]", 
    "personal_token":"[my API token from Todoist dashboard]", 
    "scope": "data:read"
  };
  var payload = JSON.stringify(data);

  var headers = {
    "Content-Type":"application/json", 
  };

  var options = { 
    "method":"POST",
    "contentType" : "application/json",
    "headers": headers,
    "payload" : payload
  };

  var response = UrlFetchApp.fetch(url, options);
  var json = response.getContentText();
  var data = JSON.parse(json);
  return(data.access_token);  

}

function getTodoistTasks(){
  var apiURL = "https://todoist.com/API/v7/sync";

  var data = {
    "token" : getTodoistToken(),
    "sync_token" : '*',
    "resource_types" : '["items"]'
  };

  var payload = JSON.stringify(data);

  Logger.log(payload);
   var headers = {
     "Content-Type":"application/json", 
   };

  var options = { 
    "method":"POST",
    "contentType" : "application/json",
    "headers": headers,
    "payload" : payload,
    "muteHttpExceptions" : true
  };

  var response = UrlFetchApp.fetch(apiURL, options);

  Logger.log(response.getContentText()); 

}
Nick S
  • 41
  • 4

2 Answers2

3

I have figured out the answer. The Todoist API documentation is bit ambiguous, seeming written around POST requests, but to download (sync) a full list of tasks, a simple URL-encoded GET request, as constructed below, did the trick:

function getTodoistTasks(){
  var apiURL = "https://todoist.com/API/v7/sync";
  var queryString = "?token=" + getTodoistTokenRev() + "&sync_token=%27*%27&resource_types=[%22items%22]";

  //Get params
  var fetchParameters = {};
  fetchParameters.method = 'get';
  fetchParameters.contentType = 'x-www-form-urlencoded';
  fetchParameters.muteHttpExceptions = true;

  //make request and return
  var response = UrlFetchApp.fetch(apiURL + queryString, fetchParameters);
  var syncData = JSON.parse(response.getContentText());
  return(syncData);
}
Nick S
  • 41
  • 4
0

And if anyone is looking for an example of creating an item (a task in this case), as I was, here's the code for that (note you need to specify a date_string and due_date for it to appear in the web UI):

var API_URL = "https://todoist.com/API/v7/sync"
var BASE_QUERY = "?token=" + TOKEN

function addTask() {

//  var taskName = SpreadsheetApp.getUi().prompt('What the task\'s name?')
  var taskName = 'Test 1652'

  var commands = encodeURI(JSON.stringify([{
    "type": "item_add", 
    "temp_id": uuidv4(),
    "uuid": uuidv4(), 
    "args": {
      "content": taskName,
      "date_string": "today",
      "due_date_utc": "2017-12-2T18:00",
    }   
  }]))

  var queryString = BASE_QUERY + '&commands=' + commands

  var options = {
    method: 'post',
    contentType: 'x-www-form-urlencoded',
    muteHttpExceptions: true}

  var response = UrlFetchApp.fetch(API_URL + queryString, options)

  if (response.getResponseCode() !== 200) {
    var content = response.getContentText()
    throw new Error('URL fetch failed: ' + content) 
  }

  var syncData = JSON.parse(response.getContentText())
  return syncData

  // Private Functions
  // -----------------

  function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

} // addTask()
Andrew Roberts
  • 2,720
  • 1
  • 14
  • 26