Todoist allows programmers to add tasks via their API. This is great if you want to integrate your other systems or web services with Todoist. However, the Todoist documentation doesn’t provide a working example and it can become tricky to figure out the right way to do it. Therefor, I created the demo script to add a task in JavaScript via the API version 7.

To make script work, you have to replace the todoist_api_token = "" with your token and the project id’s in the example task.

Script:

// Global variables
	
var todoist_api_token = ""; // Put your token here
var sync_token = "*";

/* 
 - To get a project id: click on a project and look
   at the url.
 - In the example "#project%2F2179064046" you have to
   remove "#project%2F" and the project id is 2179064046.
 - Run example task after document load

*/

window.onload = function() {
	
	console.log("Add example task to todoist");
  
	var example_tasks = [
    {"content": "Task1", "project_id": 2179064046},
    {"content": "Task2", "project_id": 2179064046}
  ];
  
	todoist_add_tasks_ajax(example_tasks);
	
}

// Functions

todoist_add_tasks_ajax = function(tasks) {
		
	var commands = todoist_tasks_to_commands(tasks);
	
	var data = {
		"token" : todoist_api_token,
		'sync_token' : sync_token,
		'resource_types' : '["projects", "items"]',
		'commands' : commands
	};
	
	jQuery.ajax({
		url: "https://todoist.com/api/v7/sync",
		data: data,
		type: "POST",
		dataType: "json",
		success: function(response) {
			console.log(response);
			sync_token = response.sync_token;
		},
		error: function(response) { 
			console.log(response);
		},
	});
	
}

todoist_tasks_to_commands = function(tasks) {
	
	var commands = [];
	
	tasks.forEach(function(args) {
		
		var temp_commands = {
			"type": "item_add",
			"temp_id": create_guid(),
			"uuid": create_guid(),
			"args": args
		};

		commands.push(temp_commands)

	});
	
	commands = JSON.stringify(commands);
	
	return commands;
	
}

function create_guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

/*

// Install jQuery

javascript: (function(e, s) {
    e.src = s;
    e.onload = function() {
        jQuery.noConflict();
        console.log("jQuery installed");
    };
    document.head.appendChild(e);
})( document.createElement('script'), 'http://code.jquery.com/jquery-latest.min.js')

*/
How to create todoist task using todoist api v7 and JavaScript?