Hello, Asana community! Thanks for having me.
This morning, I checked the forum for how to use the Batch API with the PHP client library. I saw a few posts about the Python library, but nothing really told me how to make use of this essential feature!
Well, I just figured it out, so I’d like to help others by sharing an example function.
Example Function
Here’s the function I wrote that submits a Batch request to tag and comment a task:
function tag_and_comment( string $task_gid, string $tag_gid, string $comment, string $opt_fields ) : array {
$opt_fields = explode( ',', $opt_fields );
$data = [
'actions' => [
[
'method' => 'POST',
'relative_path' => sprintf( '/tasks/%s/addTag', $task_gid ),
'data' => [
'tag' => $tag_gid,
],
'options' => [
'fields' => $opt_fields,
],
],
[
'method' => 'POST',
'relative_path' => sprintf( '/tasks/%s/stories', $task_gid ),
'data' => [
'text' => $comment,
],
'options' => [
'fields' => $opt_fields,
],
],
],
];
//$asana is the authenticated \Asana\Client instance
return $asana->post( '/batch', $data );
}
Looking at the docs for how to submit parallel requests, you’ll see that the /batch
endpoint takes an array of actions to process. Use the \Asana\Client::post()
method to post data to the endpoint.
Example Output
An array of response data per each request will be returned. For the above example, that looks like this, from a var_dump()
:
array(2) {
[0]=>
object(stdClass)#2076 (3) {
["body"]=>
object(stdClass)#2075 (1) {
["data"]=>
object(stdClass)#2074 (0) {
}
}
["status_code"]=>
int(200)
["headers"]=>
object(stdClass)#2077 (0) {
}
}
[1]=>
object(stdClass)#2080 (3) {
["body"]=>
object(stdClass)#2079 (1) {
["data"]=>
object(stdClass)#2078 (1) {
["gid"]=>
string(16) "1234567890"
}
}
["status_code"]=>
int(201)
["headers"]=>
object(stdClass)#2081 (0) {
}
}
}
Data Structure
For quick reference, the $data
for the /batch
POST request is structured like so:
$data = [
'actions' => [
[
'method' => '',
'relative_path' => '',
'data' => [
'key' => '',
...
],
'options' => [
'key' => '',
...
],
],
...
],
];
Potential Reason for “Bad Request” Response
When using the Asana Batch API in another implementation, I was repeatedly receiving the simple error message response “Bad Request”. This unhelpful error message is a real pain, but I did figure out one common point of failure: The options
value CANNOT be a CSV string. The value MUST be an array of strings. In my sample code, the explode is crucial:
$opt_fields = explode( ',', $opt_fields );
Conclusion
This batch request functionality really kicked my processing into high-gear! Its efficiency is immediately noticeable, even when testing on a super small scale.