I'm currently using Postman to do an API post request from a CRM software called Intercom. I followed the below documentation to do this:
https://developers.intercom.com/intercom-api-reference/v0/reference/creating-an-export-job
My purpose is to create a script via Google Apps Script to automate the API request.
I need to give the following elements:
- Method: Post
- URL: https://api.intercom.io/export/content/data
- Headers: Authorization : Bearer 123456789, Accept : application/json, Content-Type: application/json
- Body: "created_at_after": 1654041600, "created_at_before": 1656547200 (this is the date in Unix Timestamp)
The only parameter that will change is the body ("created_at_after" and "created_at_before"). Everything else will remain the same.
Below is the script I've created, that currently does not work. Any help on how to fix this would be appreciated. I'm quite a beginner programmer so apologies in advance if the problem is quite obvious.
function exportjob() {
var url = 'https://api.intercom.io/export/content/data';
var options = {
"Method": "post",
"Headers": {
"Authorization": "Bearer 123456789",
"Accept": "application/json",
"Content-Type": "application/json"
},
"Body": {
"created_at_after": 1654041600,
"created_at_before": 1656547200}
}
var response = UrlFetchApp.fetch(url, options);
}
CodePudding user response:
From your showing document, I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl https://api.intercom.io/export/content/data \ -X POST \ -H 'Authorization:Bearer <Your access token>' \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' -d ' { "created_at_after": 1527811200, "created_at_before": 1530316800 }'
Modification points:
- At
params
offetch(url, params)
of Class UrlFetchApp, there are no properties ofMethod
,Headers
,Body
. - In your situation, it seems that it is required to be sent the data as the string. And, by the content type of
application/json
, the data is parsed at the server side.
When these points are reflected in your script, how about the following modification?
Modified script:
function exportjob() {
var url = 'https://api.intercom.io/export/content/data';
var options = {
"method": "post",
"headers": {
"Authorization": "Bearer 123456789",
"Accept": "application/json",
},
"contentType": "application/json",
"payload": JSON.stringify({
"created_at_after": 1654041600,
"created_at_before": 1656547200
})
}
var response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText())
}
Note:
- If an error occurs for the request, please confirm your access token and the data again. And, please provide the error message.