Tags

In the last blog, I explained how it is possible to make custom calls to external API’s to fetch data. In this blog I’ll show how you can post data to an external API via a POST action.

First we add a “Code by Zapier” step as usual and then map required inputs. refer to my last blog for details.

Next we go the the actual ode section and add something like this :


var line_amount = parseFloat(inputData.line_amount);
var tax_amount = parseFloat(inputData.tax_amount);
var customer_id = Number(inputData.customer_id);

console.log("line_amount : " + line_amount + ", tax_amount : " + tax_amount + " , customer_id : " + customer_id);

var invoice =
{
"Line": [{
"Description": inputData.description,
"Amount": line_amount,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "3",
"name": "Product"
},
"UnitPrice": line_amount,
"Qty": 1,
"TaxCodeRef": {
"value": inputData.tax_code
}
}
}],
"TxnTaxDetail": {
"TxnTaxCodeRef": {
"value": "3"
},
"TotalTax": tax_amount,
"TaxLine": [{
"Amount": tax_amount,
"DetailType": "TaxLineDetail",
"TaxLineDetail": {
"TaxRateRef": {
"value": "3"
},
"NetAmountTaxable": line_amount
}
}]
},
"CustomerRef": {
"value": customer_id,
"name": inputData.customer_name
}
}

console.log("Invoice :" + JSON.stringify(invoice));

var options = {
headers:{
"Authorization": "Bearer " + inputData.access_token,
"Accept":"application/json",
"Content-Type":"application/json"
},
method : "POST",
body : JSON.stringify(invoice)

};

fetch('https://quickbooks.api.intuit.com/v3/company/123123123/invoice',options)
.then(function(res) {
console.log("response : " + res);
return res.json();
})
.then(function(json) {
var output = [{error: json.Fault, invoice:invoice, response:json}];
callback(null, output);
})
.catch(callback);

The important part to focus is the “options” passed in to fetch command where we specify the POST method, Headers and the JSON.stringify for body payload when body is of type JSON as is in the above case.

Lastly, Zapier uses fetch which uses a promise based design to process results, so we have the bunch of action->then->then code.

Enjoy!

Advertisement