How can seen the untrucated server response? [duplicate] - google-apps-script

This question already has answers here:
How can I see the full server response for this API error message in Google Scripts?
(2 answers)
Closed 6 months ago.
When using google Apps Script, sometimes I create errors on external API's I'm using.
The response is:
Exception: Request failed for https://dev1.example.com returned code 400. Truncated server response: {"code":"rest_invalid_param","message":"Invalid parameter(s): line_items","data":{"status":400,"params":{"line_items":"line_items[0][subtotal] is n... (use muteHttpExceptions option to examine full response)
I understand how to set the muteHttpExceptions :
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headers,
'muteHttpExceptions': true,
'payload': JSON.stringify(data)
};
apiurl = "https://" + apidomain + "/wp-json/wc/v3/customers/"
but I don't understand where I should then be looking for the untruncated server response.
The documentation: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app is not something I'm finding very helpful
Am I looking on the API server endpoint logs?
Or somewhere in Appscript?
Maybe here?
var response = UrlFetchApp.fetch(apiurl, options);
Logger.log(response);
Or in my local web browser?
Or am I totally confused?
I'm new to SO and Apps Script, so please be gentle.

As per this answer, the muteHttpExceptions option stops the script stopping on error, but instead puts the server error into the response of the call. This is the bit you'd usually look for your response from your API Call.
So this is how you'd get the full response, and it'd appear on the Apps Script debugging interface:
var headers = { "Authorization": "Basic " + encodedAuthInformation };
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headers, // Convert the JavaScript object to a JSON string.
'muteHttpExceptions': true,
'payload': JSON.stringify(data),
};
apiurl = "https://" + apidomain + "/wp-json/wc/v3/orders/"
var response = UrlFetchApp.fetch(apiurl, options);
Logger.log(response);

Related

Send POST request in Google Apps Script with Headers and Body

I am trying to send a POST request in order to receive an Access Token in return.
The documentation is as follows:
Client Credentials
This is your first route to obtain an access_token to communicate with the API.
Route : POST https://api.helloasso.com/oauth2/token
Headers
Content-Type = application/x-www-form-urlencoded
Body
client_id = Your Client Id
client_secret = Your Client Secret
grant_type = client_credentials
Solution I tried
Based on this post, I tried the following code:
function qwe()
{
const url = 'https://api.helloasso.com/oauth2/token';
const headers = {
"client_id": "Your Client Id",
"client_secret": "Your Client Secret",
"grant_type": "client_credentials"
};
const options = {
'method' : 'post',
'contentType': 'application/x-www-form-urlencoded',
'headers': headers
};
const response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response);
Logger.log(data);
}
Upon running this, I get an error "Exception: Request failed for https://api.helloasso.com returned code 400. Truncated server response: {"error":"unauthorized_client","error_description":"client_id is not set"}".
I am a beginner, and would appreciate any help on this! Thank you in advance
Modification points:
In the case of UrlFetchApp, the default content type is application/x-www-form-urlencoded.
From your question and situation, I guessed that your Body might be required to be sent as form data.
If those points are reflected in your script, it becomes as follows.
Modified script:
function qwe() {
const url = 'https://api.helloasso.com/oauth2/token';
const data = {
"client_id": "Your Client Id",
"client_secret": "Your Client Secret",
"grant_type": "client_credentials"
};
const options = {
'method': 'post',
'payload': data
};
const response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText())
}
Note:
If you tested this modified script, when an error occurs, please show the detailed error message and provide the official document. By this, I would like to confirm it.
Reference:
fetch(url, params)
Need to make it stringify first
'payload' : JSON.stringify(data)

Error while calling freshchat APIs from google apps script

I am trying to call FreshChat API from google apps script. GET request of outbound-messages is working fine but POST request is failing with error
Exception: Request failed for http://api.in.freshchat.com returned code 400. Truncated server response: {"success":false,"errorCode":0,"errorMessage":"HTTP 405 Method Not Allowed","errorData":null,"errorName":null} (use muteHttpExceptions option to examine full response)
Below are the details of request
function myFunctiontest() {
var url = "http://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = {
'Authorization': 'Bearer XXXXXX',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headersPOST,
'payload': JSON.stringify(bodyPayload),
'muteHttpExceptions':true
};
var response = UrlFetchApp.fetch(url, options);
console.log(response.getAllHeaders());
Logger.log(JSON.parse(response.getContentText()));
}
Same headers are working for GET request. Also same post request is working from POSTMAN.
Freshchat support helped for solving the issue.
There are two major changes
use https instead of http
Added contentType inside headers.
function myFunctiontest() {
var url = "https://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = 'Bearer XXXXXX';
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+ XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
method: 'POST',
//content-type: 'application/json',
headers: { Authorization: headersPOST, 'content-type': 'application/json'},
payload: JSON.stringify(bodyPayload),
muteHttpExceptions:true
};
var response = UrlFetchApp.fetch(url, options);
var text = response.getResponseCode();
}

Requesting access token to Zoom API via Oauth - error 'missing grant type'

I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});

Connecting to HTTPS web services API with node.js v4.2.6?

I'm looking at connecting to an https web api, I've obtained my token, and my username by receiving an email about it, and there isn't really any sample code to connect to the webservice using node; however there are examples for Java and C#, and based on those this is what I came up with...
/* WEB API: https://www.careeronestop.org/Developers/WebAPI/technical-information.aspx?frd=true */
// UserID: ...
// Token Key: ...==
// Your agreement will expire three years from today on 12/8/2019 and all Web API services will be discontinued,
// unless you renew.
var https = require('https');
var username = '...';
var tokenKey = "...==";
var options = {
host: 'api.careeronestop.org',
port: 443,
path: '/v1/jobsearch/' + username + '/Computer%20Programmer/15904/200/2',
method: 'GET',
headers: {
'Content-Type' : 'application/json',
'Authorization' : '' + new Buffer(tokenKey.toString('base64'))
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
Unfortunately however, it returns a 401 Unauthorized, so is there anything that needs added to this to get it working? Some headers maybe?
I used this form to submit a request and then looked in the Chrome debugger network tab to see exactly what request was sent.
The authorization header is supposed to look like this:
Authorization: Bearer 901287340912874309123784
You also want this:
Accept: application/json
So, assuming tokenKey is already a string since it appears to have been sent to you in an email, you can change your code to this:
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenKey
}

google apps script post basecamp

I'm trying to make calls to Basecamp's new API through Google Apps Script. GET, I can do. POST, not so much.
Starting with the path
https://basecamp.com/xxxxxxx/api/v1/projects/xxxxxxx/todolists.json
My code:
var headers = {
'User-Agent' : BCuseragent,
'Authorization' : 'Basic ' + Utilities.base64Encode(BCuser + ':' + BCpass),
'Content-Type' : 'application/json',
'Accept' : 'application/json',
'validateHttpsCertificates' : false
}
function getBC(path) {
var url = BCurl + path;
var opt = {
'headers' : headers,
'method' : "GET"
};
var response = UrlFetchApp.fetch(url, opt);
return response;
}
function postBC(path, payload) {
var url = BCurl + path;
var opt = {
'headers' : headers,
'method' : "POST",
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, opt);
return response;
}
The payload I'm passing as a parameter:
{name: "foo", description: "bar"}
The getBC function works (200 OK), the postBC function returns a 403 error. Yet I am the owner of the project, and I've used curl and a Chrome REST client to confirm I can in fact POST new todolists to this project with the same authorization.
Obviously, my headers are malformed somewhere, but I can't see how.
This is a quirk of UrlFetchApp. You can't set the Content-Type using the general "headers" parameter, instead you must use the "contentType" parameter.
See the "Advanced Parameters" table here:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)