ReferenceError: Headers is not defined in Google scripts - javascript

I am trying to automate between reply.io and Gsheets, to automatically do API calls, so I can create a 'live' dashboard in Google Sheets through script editor.
I am using the documentation on their website (https://apidocs.reply.io/#b24cfec9-3e95-4409-b520-8dfecd75e682). I only work with Python and I succeed there, but somehow I can't seem to make it work in JavaScript.
The script I use is:
function myFunction() {
var myHeaders = new Headers();
myHeaders.append("x-api-key", "{{Your_apiKey}}");
var raw = "";
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api.reply.io/v2/schedules/default", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
The error I am getting is:
ReferenceError: Headers is not defined
myFunction # Code.gs:2

Google Apps Script do not use the browser built ins, instead they have their own builtins. In this case you would need to use UrlFetchApp.
function myFunction() {
let myHeaders = {
"x-api-key": "{{Your_apiKey}}"
};
let params = {
method: 'get',
headers: myHeaders,
followRedirects : true,
};
let response = UrlFetchApp.fetch("https://api.reply.io/v2/schedules/default", params);
Logger.log(response.getContentText());
}

Related

Request for JavaScript works, but not for GoogleScreen. What's the difference?

Please, help. I can't find the error and I don't understand why the request is not working. It seems to me that it's just Google's IP blocked by the site I'm making a request to. The same request for JavaScript works.
function pleaseWork() {
var myHeaders = {
'contentType': 'application/json',
'Authorization': 'Bearer 5cd4ac65-f71b-3eaa-93af-78610a7aa320',
}
var raw = ["1111111111111"]
var requestOptions = {
'method': 'POST',
'headers': myHeaders,
'payload': JSON.stringify(raw)
};
result = UrlFetchApp.fetch("https://www.ukrposhta.ua/status-tracking/0.0.1/statuses/last", requestOptions)
Logger.log(result)
}
Working Javascript request:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer 5cd4ac65-f71b-3eaa-93af-78610a7aa320");
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify([
"1111111111111"
]);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
};
fetch("https://www.ukrposhta.ua/status-tracking/0.0.1/statuses/last", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
How to do it right?
In your Google Apps Script, the data is sent as form by default. When I saw your Javascript, it seems that the data is required to be sent as data with application/json. So you'll need to modify the script as follows.
From:
var requestOptions = {
'method': 'POST',
'headers': myHeaders,
'payload': JSON.stringify(raw)
};
To:
var requestOptions = {
'method': 'POST',
'headers': myHeaders,
'payload': JSON.stringify(raw),
'contentType': 'application/json',
};
Reference:
fetch(url, params)
Note:
I think that this modification is the same as the request of your Javascript. But, if an error occurs, please confirm your values of raw and your access token, again.
Added 1:
Your showing script was modified for testing. Please set your access token and the value of raw and test it again.
function modified_pleaseWork() {
var myHeaders = { 'Authorization': 'Bearer ###' };
var raw = ["1111111111111"];
var requestOptions = {
'method': 'POST',
'headers': myHeaders,
'payload': JSON.stringify(raw),
'contentType': 'application/json',
};
var result = UrlFetchApp.fetch("https://www.ukrposhta.ua/status-tracking/0.0.1/statuses/last", requestOptions);
Logger.log(result.getContentText())
}
Added 2:
From your following reply,
but the solution doesn't work for me. I saw you added a modified script. You can also test it with the parameter "Bearer ###" Error 403. But it is not in the JavaScript code. I don't understand what's wrong?
I confirmed the status code 403 from your reply. In this case, it is considered that the site cannot be directly accessed from the Google side. Ref I think that the reason for your issue is due to this.
But, in the case of this situation, there is a workaround. Here, I would like to propose using this workaround. Ref
Sample script:
In this case, the request is run on the custom function. By this, I thought that the status code 403 might be able to be avoided. Actually, when I tested this script using your provided access token, the result value could be obtained.
In this script, the custom function is used. So, please copy and paste the following script to the container-bound script of Google Spreadsheet. And run main(). By this, the request is run on the custom function. And, the returned value can be retrieved with the script.
function modified_pleaseWork() {
var myHeaders = { 'Authorization': 'Bearer 5cd4ac65-f71b-3eaa-93af-78610a7aa320' };
var raw = ["1111111111111"];
var requestOptions = {
'method': 'POST',
'headers': myHeaders,
'payload': JSON.stringify(raw),
'contentType': 'application/json',
};
var result = UrlFetchApp.fetch("https://www.ukrposhta.ua/status-tracking/0.0.1/statuses/last", requestOptions);
return result.getContentText();
}
// Please run this function.
function main() {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange("A1");
range.setFormula("=modified_pleaseWork()");
SpreadsheetApp.flush();
const value = range.getValue();
range.clearContent();
console.log(value)
}

How to correctly consume a rest service created with Genexus?

I have been trying to consume a simple web service crated with GeneXus, it should receive a "nPais" variable (integer) and respond an object with the text property based on the given number. It just doesn't work. I have confirm that the service work by testing it with soapUI (adding the WSDL), but when trying to consume it with postman it responds the correct structure, but with the text property empty.
This is my source tab from the WS.
&sdtServicio = New()
&Servicio.SetEmpty()
Do Case
Case &nPais = 1
&sdtServicio.Texto = "Hola México"
Case &nPais = 2
&sdtServicio.Texto = "Hola Argentina"
Otherwise
&sdtServicio.Texto = "HOLA MUNDO"
Endcase
This is on rules tab
Parm(in:&nPais, out:&sdtServicio);
And here is how I have been trying to consume the service on JS.
function getGreeting(value) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "GX_CLIENT_ID=54f383cc-0719-444d-a252-c8799c1202a0");
var raw = JSON.stringify({
"nPais": 1
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://localhost:8080/PotentorDesaPotDesa/rest/WSHolaMundo", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
This is the response I get.
{"sdtServicio":{"Texto":""}}
The trick was only to change the protocol from SOAP to internal on the properties of my object.

How to send Base64 to API

I am ultimately trying to send a fax with the Vitelity API. I have an API on EC2 that I am calling from my React Native app:
// Encoding to Base64
const encodeB64 = () => {
RNFS.readFile(croppedImage, 'base64').then(res => {
sendB64(res);
});
};
const sendB64 = b64 => {
let myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
let raw = JSON.stringify({
data1: b64, // 'jdl3439fdjsle/jjug'
login: {login},
pass: {pass},
faxnum: {destinationNum},
faxsrc: {sourceNum},
recname: 'Test',
file1: 'testfax.jpg',
});
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
};
fetch(API_URL, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
};
However, this returns an error cannot POST. If, instead of b64, I change data1's value to something like jdl3439fdjsle/jjug, everything is great.
Do I need to do something special to b64 before I can send it?
My Base64 looks like: /9j/4AA{1.2m more chars}uB//9k=. I've pasted it into a converter and it produces the correct image.
I geuss you have to use a Multipart Form with multipart/form-data as content-type headers if you want to send images. See also this question.

Module of the Headers Class/Javascript/

I'm not a technical person, so I can't code or anything, but I have to incorporate this API into google sheets.
Therefore I use this Javascript Code Sample in google Appscript. But There is no definition of the Headers.
var myHeaders = new Headers();
myHeaders.append("x-access-token", "<my gold api key>");
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://www.goldapi.io/api/XAU/EUR", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Can somebody tell me where I can find the Modul of the Headers Class and install it? Or is there another way to incorporate this API into google sheets?
Thank you for your Help!
Add these two lines at the top:
const fetch = require('node-fetch');
const { Headers } = fetch;
This is for Node-js. In a browser context your code would work without this, as the fetch API is included out of the box, and also Headers is defined.

Converting Javascript Fetch to Google Apps Script URL Fetch

Have the JavaScript code from a successful API call but when I try to change it to use Google Apps Scripts URL Fetch function I get an error.
Here's the JavaScript from successful Postman Call
...
var myHeaders = new Headers();
myHeaders.append("X-Auth-Token", "Token");
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "laravel_session=eyJpdiI6InpSaXcxVk1KQzd4cGMrT1BkWGlOQkQ0Tmt5TjhDRWRLVnlXQVwvYlJlV1EwPSIsInZhbHVlIjoiZGUyc21wWlZERHVJYkVhYks3MCswWXFOZllOQU5kSHdWeDJMbkdSZk5rNFV0N1BuUEI3N1FQT3RpbkhEU3JFRU56Wml4eE9NMmlKVGRqXC9OQ1pwNEJ3PT0iLCJtYWMiOiJjM2Q1NjBkYTAyMGFmNDY3NWJiY2VkMzZjODg0ZDViMDBlM2NmZDVkODBlMzk1YTc0ZTFlOGU4MTM3ODUxYjkxIn0%3D");
var raw = JSON.stringify({"description":"Test Description","invitees":"test#test.com","priority":"10","remind":{"popup":"0","mail":"1","hour":"09:00:00","date":"2020-12-22"},"sync_calendar":true,"task_name":"Test Name"});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://private-anon-0eef3aeb66-ricochet.apiary-mock.com/api/v4/leads/lead_id/tasks/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
...
And here is what I have in Google Apps Script
...
var raw = JSON.stringify({"description":"Test Description",
"invitees":"test#test.com",
"priority":"10",
"remind":{"popup":"0","mail":"1","hour":"09:00:00","date":"2020-12-22"},
"sync_calendar":true,
"task_name":"Test Name"});
var headers = { "X-Auth-Token" : "Token"};
var params = {
"method" : "POST",
'contentType': 'application/json',
"headers" : headers,
"payLoad" : raw
};
var url = "https://private-anon-0eef3aeb66-ricochet.apiary-mock.com/api/v4/leads/lead_id/tasks/";
var res = UrlFetchApp.fetch(url,params);
...
Here is the error I get when using Google Apps Script
Exception: Request failed returned code 500. Truncated server response: {"status":false,"message":"Validation failed"}

Categories