Guides
Sync tasks
Mirror a project's tasks in your own system. Take a cursor, list the tasks, follow the changes feed, handle deletions, and resync after a 410.
On this page
This guide keeps a local copy of a project's tasks up to date: for a search index, a data warehouse, a report or another tool. It uses two things: the task list for the starting state, and the changes feed for everything after.
You need a credential with tasks:read. The full program is at the end, in JavaScript and Python.
The plan
#- Take a cursor first.
GET /projects/{projectId}/events?after=nowreturns anextCursorthat marks this moment. - List every task. Page through
GET /projects/{projectId}/tasks?sort=createdAtand store each task byid. - Follow the feed from the cursor of step 1. For each event, fetch what it points to.
- Store the cursor after each page of events, so a restart carries on where it stopped.
- Resync if the cursor ever expires (
410).
Taking the cursor before listing is what makes this correct: a task that changes while you are still listing also produces an event after your cursor, so you catch it either way.
1. Take a cursor
#curl "https://taskloader.com/api/v1/projects/$PROJECT_ID/events?after=now" \
-H "Authorization: Bearer $TASKLOADER_API_KEY" | jq -r .nextCursorThe answer has no events (after=now starts at the present), but its nextCursor is where you will start following.
2. List the tasks
#curl "https://taskloader.com/api/v1/projects/$PROJECT_ID/tasks?sort=createdAt&limit=100" \
-H "Authorization: Bearer $TASKLOADER_API_KEY"Follow nextCursor until hasMore is false. Store every task by its id, with its version.
Sort by createdAt, which never changes. With a sort value that changes, such as position (the default) or updatedAt, a task edited while you page can move past your position and be left out of the list. Keep id as your reference: keys can be read by people, but ids are what the API resolves directly.
3. Follow the feed
#Long-poll the feed from your cursor with wait=25. Each event names a subject. For a copy of the tasks:
| Event | Do |
|---|---|
task.created, task.updated, task.moved | Fetch GET /tasks/{subject.id} and replace your copy. If data.version is not newer than the version you have, skip the fetch: you already have it, often because you made the change yourself. |
task.deleted | Remove subject.id. data.key and taskKey still say which task it was. |
tasks.reordered | If you keep board order, list the tasks again for their new position values. Nothing else changed. |
attachment.created, attachment.deleted | Fetch GET /tasks/{data.taskId} and replace your copy: its attachmentCount changed, without a new version. |
link_preview.updated | Fetch again each task whose bookmark.previewId is data.previewId: its bookmark.preview changed, without a new version. It is recorded only in the projects that asked for the read (a task there linked the page, or someone there looked at the preview 14 days after the project was last told of it), when their own turn comes, once per change: an event in every project that links the page would tell each one when another read it. A preview can therefore change without an event; read it again when you show it, or on your periodic resync. |
| Anything else | Ignore it, or refresh what else you mirror (comment.created: the task's comments; member.*: the member list; attachment.*: the task's files; project.updated: the project). |
A fetch that answers 404 means the task was deleted after the event, or you can no longer see it. Remove it either way; if it was deleted, its own task.deleted follows.
A task's version covers what people edit in it. Computed fields, such as an assignee's display name, can change with no event for the task: if you show them, refresh your copy now and then.
Unknown event types will appear over time. Skip them.
4. Store the cursor
#Write the cursor and your changes together, after each page. If your program stops between the two, it will see a few events again on restart, which is harmless: fetching a task twice changes nothing.
5. Resync after a 410
#The feed keeps events for 7 days. If your program was stopped for longer, the next request answers 410 cursor_expired. Start again from step 1: take a new cursor, list every task sorted by createdAt, and replace your copy. Tasks in your copy that the list no longer has were deleted.
If you only need to catch up on changes (not deletions), GET /projects/{projectId}/tasks?updatedSince=<time>&sort=updatedAt lists what changed since a moment, oldest change first, which is cheaper than a full list. A task changed again while you page moves to the end, so you still see it.
The whole program
#It keeps the project's tasks and the cursor in sync-<project id>.json, and handles limits, deletions and expiry.
// sync.mjs: node sync.mjs prj_… (Node.js 20 or later, no packages)
import { readFile, writeFile } from 'node:fs/promises';
const API = 'https://taskloader.com/api/v1';
const auth = { Authorization: `Bearer ${process.env.TASKLOADER_API_KEY}` };
const projectId = process.argv[2];
const stateFile = `sync-${projectId}.json`;
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
/**
* GET with limits and outages handled: waits Retry-After (or 5 seconds) on 429 and 503,
* and on the 502 and 504 pages a proxy answers in HTML.
*/
async function get(path, params = {}) {
for (;;) {
const url = new URL(API + path);
for (const [name, value] of Object.entries(params)) url.searchParams.set(name, String(value));
const response = await fetch(url, { headers: auth, signal: AbortSignal.timeout(40_000) });
if ([429, 502, 503, 504].includes(response.status)) {
await sleep(Number(response.headers.get('retry-after') ?? 5));
continue;
}
return { status: response.status, body: await response.json() };
}
}
const fail = ({ status, body }) => {
throw new Error(`${status} ${body.code}: ${body.detail}`);
};
async function listTasks() {
const tasks = {};
let cursor = null;
do {
// createdAt never changes, so no task can move past the cursor while we page.
const page = await get(`/projects/${projectId}/tasks`, {
sort: 'createdAt',
limit: 100,
...(cursor && { cursor }),
});
if (page.status !== 200) fail(page);
for (const task of page.body.data) tasks[task.id] = task;
cursor = page.body.nextCursor;
} while (cursor);
return tasks;
}
async function fullSync() {
const head = await get(`/projects/${projectId}/events`, { after: 'now' }); // The cursor first.
if (head.status !== 200) fail(head);
return { cursor: head.body.nextCursor, tasks: await listTasks() };
}
/** Replaces the copy of one task, or drops it when it is gone. */
async function refresh(state, id) {
const task = await get(`/tasks/${id}`);
if (task.status === 404) delete state.tasks[id];
else if (task.status === 200) state.tasks[id] = task.body;
else fail(task);
}
async function apply(state, event) {
if (event.type === 'tasks.reordered') {
state.tasks = await listTasks();
return;
}
// These change a task's attachmentCount or bookmark preview without a new version.
if (event.type === 'attachment.created' || event.type === 'attachment.deleted') {
await refresh(state, event.data.taskId);
return;
}
if (event.type === 'link_preview.updated') {
for (const task of Object.values(state.tasks))
if (task.bookmark?.previewId === event.data.previewId) await refresh(state, task.id);
return;
}
if (event.subject.type !== 'task') return; // Comments, members: refresh them here if you mirror them.
const id = event.subject.id;
if (event.type === 'task.deleted') {
delete state.tasks[id];
return;
}
const known = state.tasks[id];
if (known && typeof event.data.version === 'number' && event.data.version <= known.version)
return;
await refresh(state, id);
}
let state;
try {
state = JSON.parse(await readFile(stateFile, 'utf8'));
} catch {
state = await fullSync();
await writeFile(stateFile, JSON.stringify(state));
}
console.log(`${Object.keys(state.tasks).length} tasks; following changes…`);
for (;;) {
const page = await get(`/projects/${projectId}/events`, {
after: state.cursor,
wait: 25,
limit: 200,
});
if (page.status === 410) {
state = await fullSync(); // Stopped for more than 7 days: rebuild.
} else if (page.status === 200) {
for (const event of page.body.data) {
await apply(state, event);
console.log(event.type, event.taskKey ?? event.subject.id);
}
state.cursor = page.body.nextCursor;
} else fail(page);
await writeFile(stateFile, JSON.stringify(state));
}# sync.py: python3 sync.py prj_… (needs requests)
import json
import os
import sys
import time
import requests
API = "https://taskloader.com/api/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['TASKLOADER_API_KEY']}"
project_id = sys.argv[1]
state_file = f"sync-{project_id}.json"
def get(path, **params):
"""GET with limits and outages handled: waits Retry-After (or 5 seconds) on 429 and 503,
and on the 502 and 504 pages a proxy answers in HTML."""
while True:
response = session.get(API + path, params=params, timeout=40)
if response.status_code in (429, 502, 503, 504):
time.sleep(int(response.headers.get("Retry-After", "5")))
continue
return response.status_code, response.json()
def fail(status, body):
raise RuntimeError(f"{status} {body['code']}: {body['detail']}")
def list_tasks():
tasks, cursor = {}, None
while True:
# createdAt never changes, so no task can move past the cursor while we page.
params = {"sort": "createdAt", "limit": 100, **({"cursor": cursor} if cursor else {})}
status, page = get(f"/projects/{project_id}/tasks", **params)
if status != 200:
fail(status, page)
tasks.update({task["id"]: task for task in page["data"]})
cursor = page["nextCursor"]
if not cursor:
return tasks
def full_sync():
status, head = get(f"/projects/{project_id}/events", after="now") # The cursor first.
if status != 200:
fail(status, head)
return {"cursor": head["nextCursor"], "tasks": list_tasks()}
def refresh(state, task_id):
"""Replaces the copy of one task, or drops it when it is gone."""
status, task = get(f"/tasks/{task_id}")
if status == 404:
state["tasks"].pop(task_id, None)
elif status == 200:
state["tasks"][task_id] = task
else:
fail(status, task)
def apply(state, event):
if event["type"] == "tasks.reordered":
state["tasks"] = list_tasks()
return
# These change a task's attachmentCount or bookmark preview without a new version.
if event["type"] in ("attachment.created", "attachment.deleted"):
refresh(state, event["data"]["taskId"])
return
if event["type"] == "link_preview.updated":
for task in list(state["tasks"].values()):
if (task["bookmark"] or {}).get("previewId") == event["data"]["previewId"]:
refresh(state, task["id"])
return
if event["subject"]["type"] != "task":
return # Comments, members: refresh them here if you mirror them.
task_id = event["subject"]["id"]
if event["type"] == "task.deleted":
state["tasks"].pop(task_id, None)
return
known = state["tasks"].get(task_id)
version = event["data"].get("version")
if known and isinstance(version, int) and version <= known["version"]:
return
refresh(state, task_id)
def save(state):
with open(state_file, "w") as file:
json.dump(state, file)
try:
with open(state_file) as file:
state = json.load(file)
except FileNotFoundError:
state = full_sync()
save(state)
print(f"{len(state['tasks'])} tasks; following changes…")
while True:
status, page = get(f"/projects/{project_id}/events", after=state["cursor"], wait=25, limit=200)
if status == 410:
state = full_sync() # Stopped for more than 7 days: rebuild.
elif status == 200:
for event in page["data"]:
apply(state, event)
print(event["type"], event["taskKey"] or event["subject"]["id"])
state["cursor"] = page["nextCursor"]
else:
fail(status, page)
save(state)Going further
#- Many projects: run one long-poll loop per project. An idle loop makes 2 or 3 requests a minute against your search limit, so one credential can follow a few dozen projects this way (see Limits). Beyond that, poll without
wait, which counts against your read limit instead: with N projects, leave at least N/5 seconds between rounds, which keeps half the read limit free for fetching tasks. - Fewer fetches: when a page has many events, collect the task ids first and fetch each task once. For up to 50 tasks at a time,
GET /projects/{projectId}/tasks?keys=TL-1,TL-5,…returns them in one request. - Comments and history:
GET /tasks/{taskId}?include=comments,activity,linksreturns a task with its newest 20 comments and 20 history entries, andhasMorewhen there are more; continue with the cursors it returns inGET /tasks/{taskId}/comments?order=newestandGET /tasks/{taskId}/activity. Itslinksare the bookmark and the first 10 links in the description, whole, without a cursor (moreLinksInDescriptionsays when the description holds more). Addattachmentstoincludewhen the credential hasfiles:read(the full list isGET /tasks/{taskId}/attachments). A task read withincludecarries noETag. - Access: if the person behind the credential leaves the project, the feed answers
404. Stop syncing and tell them. - Writes: when your program changes tasks too, use the version from your copy in
If-Match, and see Conflicts and retries.