Asana API Event not returning new Sync - python

Hi Team,
When we are trying to trigger the events end point using the existing sync, the response payloads contains only the DATA element. The new Sync generated is not getting returned to the calling program.

Below is the code snippet.
import asana
client = asana.Client.access_token(personal_access_token)
result = client.events.get_events(opt_fields=[“resource”,“sync”], resource=project_gid, sync=sync)

while True:
try:
resource = next(result)
if resource[‘resource’][“resource_type”] == “task”:
changed_tasks.append(resource[‘resource’][“gid”])
except StopIteration as f:
break

Please advise how to get the Sync attribute to be included in the response. Thanks in advance!

2 Likes

Same issue here, using asana==4.0.11 with the latest API changeset,

    config = asana.Configuration()
    config.access_token = os.getenv("API_KEY")
    client = asana.ApiClient(config)
    events_session = asana.EventsApi(client)

    events = events_session.get_events(
            resource = os.getenv("PROJECT_ID"),
            sync = "some_token",
            )

Getting this as response:

{'data': [], 'next_page': None}

Hey, just found a solution finally! The asana python module is just not it right now, getEvents() doesn’t return sync tokens, so I looked around & got good results by just using requests, here’s a local script example:

import os
import requests
import json
from typing import Optional

class AsanaEventListener:
    def __init__(self,PROJECT_GID:str,sync_token:Optional[str] = None):
        self.init_local_dirs()
        self.PROJECT_GID= PROJECT_GID
        self.headers = self.build_headers()
        self.sync_token = sync_token or self.cache_sync_token() or self.get_sync()
        self.url = self.build_url()

    def init_local_dirs(self):
        if not os.path.exists("./cache"):
            os.mkdir("cache")
        if not os.path.exists("./storage"):
            os.mkdir("storage")

    def cache_sync_token(self) -> str:
        if not os.path.exists("./cache/syncToken.txt"):
            return self.get_sync()
        with open("./cache/syncToken.txt","r") as reader:
            st = reader.read()
        print("Using cached sync token")
        return st

    def build_url(self):
        return f"https://app.asana.com/api/1.0/projects/{self.PROJECT_GID}/events?sync={self.sync_token if self.sync_token else ''}"

    def get_sync(self):
        base_sync_url = f"https://app.asana.com/api/1.0/projects/{self.PROJECT_GID}/events"
        resp = requests.get(
                base_sync_url,
                headers = self.headers
                )

        return json.loads(resp.content)["sync"]

    def build_headers(self):
            return {
                "accept": "application/json",
                "authorization": f"Bearer {os.getenv('API_KEY')}"
            }

    def store_sync_token(self,sync_token:str) -> None:
        with open("./cache/syncToken.txt","w") as writer:
            writer.write(sync_token)


    def request_current_events(self,recursed:bool=False):
        with requests.Session() as session:
            resp = session.get(self.url,headers = self.headers)
            json_response = json.loads(resp.content)
            resp_keys = list(json_response.keys())
            if ("errors" in resp_keys) & ("sync" in resp_keys):
                print("Bad sync token, re-checking", json_response)
                self.get_sync()
                if recursed:
                    raise requests.RequestException("Unable to fulfill requests, invalid sync tokens")
                return self.request_current_events(recursed=True)
        self.store_sync_token(json_response["sync"])
        self.sync_token = json_response["sync"]
        return json_response

1 Like

Hi @Augmen_Digital_Dev,

Our Get events on a resource (GET /events) endpoint has a weird behavior. We actually return the sync token in the error message for 412 Precondition Failed.

When you make an initial request to GET /events you will get a 412 Precondition Failed error which will return the sync token in the error message of the response.

We have an example of capturing this error in our python-asana README.md for python v4.0.11 here

1 Like