API with Python - Create Task and add it to a Project


Hi! We have an api in python that is set up to create a project for a request coming in from Knack. We want to have one of the tasks get added to a project that is already created, but I’ve looked at the information and it’s not really coded in the same way our code is.

    def create_tasks(self, tasks, project_id):
    resolved_tasks = self.resolve_tasks(tasks)

    section_id = None
    created_task_ids = []

    for task in resolved_tasks:
            if section_id is not None:
                task['memberships'] = [{'project': project_id, 'section': section_id}]
            task['projects'] = [project_id]

            custom_fields = {}
            estimated_hours = task.pop('estimated_hours', None)
            if estimated_hours is not None:
                custom_fields[self.estimated_hours_field_id] = estimated_hours
                task['custom_fields'] = custom_fields

            subtasks = task.pop('subtasks', ())
            res = self.asana.tasks.create(task)
            for subtask in subtasks:
                sub_res = self.asana.tasks.add_subtask(res['id'], subtask)
        except Exception:
            logging.exception('Exception while creating task {}'.format(task))

        if task['name'].endswith(':'):
            section_id = res['id']

        **if task['name'].endswith('Status'):**

** addProject[‘memberships’] = [{‘project’: #####, ‘section’: #####}]**

    return created_task_ids

- I found the number and the section but didn’t want to post them…

Also it’s not breaking from sending the tasks to asana, it just doesn’t add them.

1 Like


So the task gets added but does not belong to the project it should? And you have the permission to add tasks to the project?



The user that creates the project has permission to add tasks to the project. Not everyone does, but the “user” that creates tasks through the api does.

Correct, the new tasks are created in a new project, and one of those tasks needs to be added to the Status project as well



I don’t know then. There is an endpoint to add a task to a project, maybe you should try.



Hi @Erika_Donovan_Asana, I believe the issue is with your use of memberships. This is a create-only field in the API—to add a task to a project after you have created it, you must call POST /tasks/<task-id>/addProject.