Skip to content

Instantly share code, notes, and snippets.

@krharsh17
Created January 1, 2023 23:25
Show Gist options
  • Save krharsh17/585d54e60dc808607d7587a7ff3b22b7 to your computer and use it in GitHub Desktop.
Save krharsh17/585d54e60dc808607d7587a7ff3b22b7 to your computer and use it in GitHub Desktop.
Python Script to Interact with the Asana API
import requests
import csv
import sys
PAT_TOKEN = "<Your Token Here>"
BASE_URL = 'https://app.asana.com/api/1.0'
USERS_ENDPOINT = '/users/me'
TASKS_ENDPOINT = '/tasks'
# A function to retrieve the default workspace and user IDs to use when creating and fetching tasks
# In a real-world scenario, you'd fetch all available workspace and user IDs and use them to filter/create new tasks
def getIds():
result = requests.get(
BASE_URL + USERS_ENDPOINT,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {}'.format(PAT_TOKEN) # Adding the PAT token for authentication
}
)
data = result.json()
workspaceId = data["data"]["workspaces"][0]["gid"]
assigneeId = data["data"]["gid"]
return workspaceId, assigneeId
# A function to create new tasks in Asana from data stored in an input.csv file
def createTasks():
workspaceId, assigneeId = getIds()
with open('./input.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
data = {
"data": {
"name": row[0].strip(), # Fetch from input file and strip any extra whitespaces from the text
"notes": row[1].strip(),
"due_on": row[2].strip(),
"workspace": workspaceId, # Add the default workspace ID
"assignee": assigneeId # Assign the task to the current user
}
}
result = requests.post(
BASE_URL + TASKS_ENDPOINT,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {}'.format(PAT_TOKEN) # Adding the PAT token for authentication
},
json=data
)
print(result.json())
# A function to fetch all tasks under the default workspace assigned to the current user
def getAllTasks():
workspaceId, assigneeId = getIds()
result = requests.get(
BASE_URL + TASKS_ENDPOINT +
'?workspace={}&assignee={}'.format(workspaceId, assigneeId),
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {}'.format(PAT_TOKEN) # Adding the PAT token for authentication
}
)
data = result.json()["data"]
print("Total number of tasks", len(data))
print("Tasks ->")
print(data)
if (len(sys.argv) > 1 and sys.argv[1] == 'FETCH'):
getAllTasks()
elif (len(sys.argv) > 1 and sys.argv[1] == 'CREATE'):
createTasks()
# To invoke the functions, run either `python3 script.py FETCH` or `python3 script.py CREATE` on the command line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment