Invalid JSON response from batch API request

Hi all,

I am using Google Apps Script to send a batch API request to add a story and some attachments to a task. Here is the code:

function add_details(asana_id, desc, files){
  var actions = []
  if(desc != ""){
    var action = {
      "data": {
        "text": desc
      },
      "method": "POST",
      "relative_path": "/tasks/" + asana_id + "/stories"
    }
    actions.push(action)
  }
  if(files.length > 0){
    for(var file_num = 0; file_num < files.length; file_num++){
      var action = {
        "data": {
          "file": files[file_num]
        },
        "method": "POST",
        "relative_path": "/tasks/" + asana_id + "/attachments"
      }
    }
    actions.push(action)
  }
  
  var url = "https://app.asana.com/api/1.0/batch"
  var headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Authorization": "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  };
  var options = {
    "method": "POST",
    "headers": headers,
    "payload": {
      "actions": actions
    },
    "muteHttpExceptions": true
  };
  console.log(options.payload)
  var response = UrlFetchApp.fetch(url, options);
  var json = JSON.parse(response.getContentText());
  console.log(json)

  if(json.errors) {
    throw "There was an error adding the description"
  }
  else {
    return "Success"
  }
}

Here is an example of the payload JSON:

{ actions: 
   [ 
     {
        "data": {
          "text": "This is a test for batch API" 
        },
        "method": "POST",
        "relative_path": "/tasks/111111111111111111111/stories" 
     },
     {
        "data": {
          "file": { [file_object] }
        }, 
        "method": "POST",
        "relative_path": "/tasks/111111111111111111111/attachments"
     }
   ]
}

But when I send this request to Asana, I am getting an invalid JSON response, with a message saying “Could not parse request data, invalid JSON”

I’m not sure what it is that I’m missing, has anyone got any ideas?

Thanks!

You can’t POST an attachment to a task using the batch endpoint.

From the documentation:

Restrictions
Not every endpoint can be accessed through the batch API. Specifically, the following actions cannot be taken and will result in a 400 Bad Request for that action:

Uploading attachments
Creating, getting, or deleting organization exports
Any SCIM operations
Nested calls to the batch API

1 Like

Ah, thanks Frederic, clearly I missed that part of the docs!

1 Like