Google Apps Script GraphQL API Call - javascript

I've been working with the Canvas REST API and ran into some limitations and was directed to their experimental GraphQL API. Given its experimental nature, they have little to no documentation on it. Despite its advantages for what I'm building, I can't find a whole lot on the internet either. As of right now, I can't even get a basic query to work.
function testsendgraphql() {
const url = "https://hsccsd.beta.instructure.com:443/api/graphql";
const payload = `
query {
course(id: 1234) {
{
name
}
}
}`;
const options = {
"method": "POST",
"headers": { "Content-Type": "application/json", "Authorization": "Bearer "+getcanvasaccesstoken() },
"body": payload
};
Logger.log(query);
apiresponse = UrlFetchApp.fetch(url,options);
var head = apiresponse.getAllHeaders();
var data = JSON.parse(apiresponse.getContentText());
Logger.log(data);
Logger.log(head);
}
Running the above gets a response code of 200 but gives the following message:
{errors=[{message=No query string was present}]}
Something with my formatting of the payload seems to be off. Any help would be greatly appreciated.

I recently had success with the following GraphQL query using Google Apps Script:
function test(query) {
var url = "https://gql.waveapps.com/graphql/public";
var options = {"headers": {"Authorization": "Bearer " + getAccessToken(),
"Content-Type": "application/json"
},
"payload": JSON.stringify({query}),
"method": "POST"
}
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
return;
}
where the query that was passed into the function was formatted as follows:
var query = "query { user { id defaultEmail } }";

You must JSON.stringify your query and post it as payload.

I had a similar error to yours, that there was no query string present. It may be because GraphQL is looking in the URL arguments for the query, not in the HTTP request payload.
For example, get rid of the payload and change your URL to:
var url = encodeURI("https://gql.waveapps.com/graphql/public?query=query{course(id:1234){{name}}}");
Or maybe
var url = encodeURI("https://gql.waveapps.com/graphql/public?query={course(id:1234){{name}}}");
This was brought to my attention by this answer.

Related

Sending media parameter is not working while sending it to kaleyra api through code

https://developers.kaleyra.io/docs/send-a-media-template-message-through-whatsapp
I am trying to send a media to kalerays api through my code. But it is not working when I pass from code. But When I hit the API from postman then it works fine.
async whatsappAPIWithAttachment(requestBody) {
let api_key = "";
if (requestBody.campaign) {
api_key = "x";
} else {
api_key = "Y";
}
var data = qs.stringify({
from: "xyz",
to: "xyz",
type: "mediatemplate",
channel: "whatsapp",
template_name: "xyz",
params: '"name","vendor"',
lang_code: "en",
media_url: "http://www.africau.edu/images/default/sample.pdf",
});
var config: AxiosRequestConfig = {
method: "post",
url: "https://api.kaleyra.io/v1/HXIN1707222213IN/messages",
headers: {
"api-key": api_key,
"content-type": "multipart/form-data",
},
data: data,
};
let response = await axios(config);
return response.data;
}
}
It gives me an enter image description hereerror request failed with status code 400. Here I have replaced X, Y, and XYZ with actual parameters. So Inputs are correct but still get an error saying 'E413', message: 'Invalid/incorrect inputs.
As per sample request in kaleyra documentation, they have used
--header 'Content-Type: application/json'
while you are passing
"content-type": "multipart/form-data",
pls correct it and try.
how about using double quote strings for param value
params: "\"name\",\"vendor\""

blank gravity form entries with API

I'm trying to create an entry in a Gravity form via API post in Google Apps script.
An entry gets created but the values are showing blank. any insight of where I'm possibly going wrong would be appreciated.
Below is my code:
function gravityForms(){
const url = 'https://example.com/wp-json/gf/v2/forms/18/entries';
const payload = [{"2":"My name"}];
const options = {
"method" : "post",
"payload" : JSON.stringify(payload),
"muteHttpExceptions" : true
};
options.headers = {
"Content-Type" : "application/json",
"Authorization" : "Basic " + Utilities.base64Encode("ck_xxxxxxxxxxxx:cs_xxxxxxxxxxxxxxxxxx")
};
const res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
}
This is the response I get back in the logger
{"0":{"2":"My name"},"form_id":18,"id":3320}
I removed the [] from the entry object and it worked. funny since the examples show to add them.

No response from API

I have created an API call in excel to get data from a Wix database.
The call:
Dim http As Object, JSON As Object
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://username.wixsite.com/mysite/_functions/Functionname", False
http.setRequestHeader "Authorization", "myauthkey"
http.Send
MsgBox (http.responseText)
The javascript http backend file on Wix:
import { ok, notFound, serverError } from 'wix-http-functions';
import wixData from 'wixdata';
export function get_Wixdata() {
let options = {
"headers": {
"content-type": "application/json"
}
};
return wixData.query("wix data collection name")
.find()
.then(results => {
if (results.items.length > 0) {
options.body ={
"items": results.items
}
return ok(options);
}
})
}
I tested the call (without authorisation) on JSON place holder and it worked fine.
Just trying to debug what's happening as I am getting "" as a response.
Even if I enter the wrong API key I still get "", even a wrong url it's still a "" response.
I take it I am clearly way off the mark with what I am trying to do..
Did you tried put both headers in your request, like the following:
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': '....'
});
The issue was with the VBA call, the header was not needed.
Dim https As Object, JSON As Object
Set https = CreateObject("MSXML2.XMLHTTP")
With CreateObject("Microsoft.XMLHTTP")
.Open "GET", "end point url", False
.send
response = .responseText
End With

Trouble returning API response leveraging fetch

Been working on a script to execute in Google Apps Scripts to pull some data from an external API and post that information into a Google Sheet. I have a script that works client side (running from the console in chrome) that is able to leverage promises and return HTTP responses correctly to execute more code on.
However, in Apps Scripts I cannot figure out how to return a native JSON object representation from the API. In normal JS, I would return the .json() method of the response and would be good to go. Since Apps Script is essentially executing a .gs file they have different classes and methods that are not specific to JS. This help doc https://developers.google.com/apps-script/guides/services/external provides the below example for working with JSON
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data.title);
If I try to leverage that getContextText() method by itself I get a TypeError: Cannot read property '0' of undefined error. If I combine it with JSON.parse like return JSON.parse(response.getContentText()); I get a SyntaxError: Unexpected token M in JSON at position 0. Am I missing something wildly obvious? Any help would be greatly appreciated! Additionally, happy to provide more specifics from my script as well.
EDIT
Below is a snippet of script that works client side.
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': "Basic" + ' ' + gongCreds,
'Accept': "*/*",
'Connection': "keep-alive",
'Content-Type': "application/json"
},
body: gongRequestBody,
});
return response.json();
}
Here is the returned promise object data that I want to leverage for future execution
[[PromiseResult]]: Object
records: {totalRecords: 1, currentPageSize: 1, currentPageNumber: 0}
requestId: "6w83fpcbo5ka2evast7"
usersDetailedActivities: Array(1)
0:
userDailyActivityStats: Array(1)
0:
callsAsHost: []
callsAttended: (6) ["432806286570218902", "1825323793748204011", "3193437184015561879", "4172384470445855263", "5128172192322468435", "5808052479141116583"]
callsCommentsGiven: []
callsCommentsReceived: []
callsGaveFeedback: []
callsMarkedAsFeedbackGiven: []
callsMarkedAsFeedbackReceived: []
callsReceivedFeedback: []
callsRequestedFeedback: []
callsScorecardsFilled: []
callsScorecardsReceived: []
callsSharedExternally: []
callsSharedInternally: []
fromDate: "2021-01-20T05:00:00Z"
othersCallsListenedTo: (2) ["3401282086024720458", "8098199458721511977"]
When your following Javascript is converted to Google Apps Script,
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': "Basic" + ' ' + gongCreds,
'Accept': "*/*",
'Connection': "keep-alive",
'Content-Type': "application/json"
},
body: gongRequestBody,
});
return response.json();
}
it becomes as follows.
const response = UrlFetchApp.fetch(url, {
method: 'POST',
headers: {
'Authorization': "Basic" + ' ' + gongCreds,
'Accept': "*/*",
'Connection': "keep-alive",
},
muteHttpExceptions: true,
contentType: "application/json",
payload: gongRequestBody,
});
console.log(response.getContentText())
// I think that if above request works and the returned value is the correct value you expected, you can use console.log(JSON.parse(response.getContentText()).title)
But, there are several important points.
From your script, I cannot see the value of gongRequestBody. When 'Content-Type': "application/json" is used, JSON.stringify() is required to be used for the JSON object. So if gongRequestBody is the JSON object, please convert it to the string using JSON.stringify().
From your question, I cannot see your script for requesting to the URL. So I cannot point out the modification points of your script even when your script has the modification points.
I asked to show the sample value of response.getContentText() in your Google Apps Script. But unfortunately, I cannot find the sample value of it. So when you use console.log(JSON.parse(response.getContentText()).title) to the above sample script of Google Apps Script and an error occurs, can you provide the sample value of console.log(response.getContentText())? By this, I would like to confirm it.
Note:
In this sample script, it supposes that your Javascript works and the variables of gongCreds, gongCreds and gongRequestBody are the valid values for requesting to your URL. Please be careful this. So when above sample script didn't work as you expected, can you provide the sample value of console.log(response.getContentText())? By this, I would like to confirm your situation.
Reference:
fetch(url, params)

POST projects in Toggl through API

I'm developing an API to integrate the Knack with Toggl. So, I need to post some data in the Toggl using an API that will be running in Google Script (JavaScript).
When I try to post somes projects in the Toggl, I receive the following error: "Request failed for https://www.toggl.com/api/v8/projects returned code 400. Truncated server response: Project can't be blank (use muteHttpExceptions option to examine full response) (line 61, file "")"
My source code is:
function sendDataToToggl(){
var apiToken = '936e292eaccd99b40358edea25452880';
var unamepass = apiToken + ":api_token";
var digest = Utilities.base64Encode(unamepass);
var digestfull = "Basic " + digest;
var url = "https://www.toggl.com/api/v8/projects";
var data = {"project":{"name":"An awesome project","wid":1034130,"template_id":1793088,"is_private":true,"cid":123397}};
var options = {
"Content-Type": "application/json",
"method": "post",
"headers": {"Authorization": digestfull},
"payload": data
//"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
}
Change options:
Content-Type to contentType - https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
"payload": data to "payload": JSON.stringify(data) - will generate JSON string as payload.
Also, as you publicly posted your API key, you might want to get a new one.

Categories

Resources