Reputation: 1
I try to get info from an API using UrlFetchApp. I tried the GET and POST commands in POSTMAN and it work fine. In Google Apps Script the first one works and the second one return Error 404.
function pru_demo() {
// Log In.
var options = {
'method' : 'POST',
'contentType': 'application/json'
};
var response=UrlFetchApp.fetch('https://demo.erpnext.com/api/method/[email protected]&pwd=demo', options);
var data=JSON.parse(response)
Logger.log(data.full_name);
// Get Employes
options = {
// 'muteHttpExceptions' : true,
'method' : 'GET',
'contentType': 'application/json'
};
response=UrlFetchApp.fetch('https://demo.erpnext.com/api/resource/Employee', options);
Logger.log(response.getContentText());
}
Upvotes: 0
Views: 1210
Reputation: 2170
When you send the initial login request, the server returns cookies that are used for the session. You need to extract those cookies and set them on all your subsequent requests.
I've amended your code to demonstrate this:
function pru_demo() {
// Log In.
var options = {
'method' : 'POST',
'contentType': 'application/json'
};
var response=UrlFetchApp.fetch('https://demo.erpnext.com/api/method/[email protected]&pwd=demo', options);
var data = JSON.parse(response)
Logger.log(data.full_name);
// Extract the cookies from the login response
var cookies = response.getAllHeaders()['Set-Cookie'];
var cookieParts = [];
for (var i = 0; i < cookies.length; i++) {
var arr = cookies[i].split('; ');
cookieParts.push(arr[0]);
}
// Create a new cookie to send with subsequent requests
var newCookie = cookieParts.join('; ');
Logger.log(newCookie);
// Get Employes
options = {
// 'muteHttpExceptions' : true,
'method' : 'GET',
'contentType': 'application/json',
'headers': {
'Cookie' : newCookie
}
};
response = UrlFetchApp.fetch('https://demo.erpnext.com/api/resource/Employee', options);
Logger.log(response.getContentText());
}
Upvotes: 3