Reputation: 25
I'm trying to automate an API request into Google spreadsheets using Apps Script, the GET request seems to work fine in python, but when I try to replicate the same request using UrlFetchApp.fetch
method it throws a 422 error, ignoring headers apparently.
Here is the working python code:
url = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token={}".format(token)
r = requests.get(url = caixa, params= {'data_inicio' : '2018-01-01',
'data_fim' : '2022-02-01',
'regime':'caixa'})
But when I try to replicate it to Apps Script, it seems to ignore those parameters
var link = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token=my_access_token";
headers = {
'data_inicio': '2020-01-01',
'data_fim': '2020-06-30',
'regime': 'caixa',
};
var options = {
"method" : "get",
"contentType":"application/json",
'headers': headers,
};
Logger.log(options);
var res = UrlFetchApp.fetch(link, options)
It throws the following error message:
Exception: Request failed for https://api.granatum.com.br returned code 422. Truncated server response: {"errors":{"data_inicio":["é obrigatório"],"data_fim":["é obrigatório"],"regime":["é obrigatório","inválido"]}} (use muteHttpExceptions option to examine full response)
Translating the response, it asks for those three parameters informed above, as if it haven't received them.
Upvotes: 1
Views: 165
Reputation: 201513
I believe your goal as follows.
You want to convert the following python script to Google Apps Script.
url = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token={}".format(token)
r = requests.get(url = caixa, params= {'data_inicio' : '2018-01-01', 'data_fim' : '2022-02-01', 'regime':'caixa'})
url
is "https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token={}".format(token)
. But requests
uses url = caixa
. But, from your Google Apps Script, in this answer, it supposes that you are using url
.When you want to use url
in above script, how about the following modification?
params
are sent as the query parameter. But in your script, these values are sent in the request header.When above points are reflected to Google Apps Script, it becomes as follows.
function myFunction() {
// This is from https://gist.github.com/tanaikech/70503e0ea6998083fcb05c6d2a857107
String.prototype.addQuery = function(obj) {
return this + Object.keys(obj).reduce(function(p, e, i) {
return p + (i == 0 ? "?" : "&") +
(Array.isArray(obj[e]) ? obj[e].reduce(function(str, f, j) {
return str + e + "=" + encodeURIComponent(f) + (j != obj[e].length - 1 ? "&" : "")
},"") : e + "=" + encodeURIComponent(obj[e]));
},"");
}
var url = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa";
var query = {
'data_inicio': '2020-01-01',
'data_fim': '2020-06-30',
'regime': 'caixa',
'access_token': 'my_access_token'
};
var res = UrlFetchApp.fetch(url.addQuery(query));
Logger.log(res.getContentText());
}
url
. And, it supposes that your access token can be used. Please be careful this.Upvotes: 1