javascriptapigoogle-apps-scriptasanaasana-api

Batch Request to Asana API in JavaScript


I for some reason can't get the formatting to work when I submit a Batch API request to the Asana API. Below are 2 sections, the first of which is how I normally would send a single request to the Asana API, as well as their documentation for how to do so, so that you can see how my code relates to what they specify. The second section is my attempt at submitting a batch request and again their documentation of how to do so.

Single Request

Their documentation here

My code (works perfectly)

const url1 = baseURL + '/tasks'

const payload1 =
{
  name: 'Test Task 1',
  projects: projectGID,
}

const options1 =
{
  method: "POST",
  headers: headers,
  payload: payload1,
  muteHttpExceptions: true
}

const resp1 = UrlFetchApp.fetch(url1, options1)

Logger.log(resp1)

Batch Request

Their Batch Request Documentation (can scroll up a bit from this link to get more info if needed)

My code (error message: "Bad Request")

const url2 = baseURL + '/batch'

const payload2 =
{
  actions:
  [
    {
      data:
      {
        name: 'Test Task 1',
        projects: projectGID
      },
      method: "post",
      relative_path: "/tasks"
    },
    {
      data:
      {
        name: 'Test Task 2',
        projects: projectGID
      },
      method: "post",
      relative_path: "/tasks"
    }
  ]
}

const options2 =
{
  method: "POST",
  headers: headers,
  payload: payload2,
  muteHttpExceptions: true
}

const resp2 = UrlFetchApp.fetch(url2, options2)

Logger.log(resp2)

Solution

  • I believe your goal is as follows.

    Modification points:

    When these points are reflected in your script, it becomes as follows.

    Modified script:

    function myFunction() {
      const projectGID = "###"; // Please set your value.
      const headers = {
        "Authorization": "Bearer ###", // Please set your access token.
        "Accept": "application/json",
      }
      const url2 = "https://app.asana.com/api/1.0/batch";
    
      const payload2 = { // Modified
        data: {
          actions:
            [
              {
                data:
                {
                  name: 'Test Task 1',
                  projects: projectGID
                },
                method: "post",
                relative_path: "/tasks"
              },
              {
                data:
                {
                  name: 'Test Task 2',
                  projects: projectGID
                },
                method: "post",
                relative_path: "/tasks"
              }
            ]
        }
      };
      const options2 = {
        method: "POST",
        headers: headers,
        payload: JSON.stringify(payload2), // Modified
        muteHttpExceptions: true,
        contentType: "application/json", // Added
      }
      const resp2 = UrlFetchApp.fetch(url2, options2)
      Logger.log(resp2)
    }
    

    Note:

    References: