Graphql query with $http.post does not work - javascript

The request for the code below goes all ok but I don't get any data back (Just says "Error Not Found" in the "preview" tab of the request in chrome). I try the same query in GraphiQL and it gives back relevant data. I am not sure what I am missing here. Please advise, kind of stuck with this.
PlayService.prototype.getPlays = function(playID) {
//The query.
const playsQuery = `query ($playid: String) {
plays(id: $playid) {
id
items {
nodes {
id
name
}
}
}
}`;
// variables to pass.
const variables = {
playid: playID
};
//The request.
const result = $http.post(
/graphql,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ playsQuery, variables })
}
);
return result && result.data;
};

You appear to be sending the data body as:
{
playsQuery: "<query string>",
variables: {}
}
The GraphQL spec specifies that you must follow this format for GraphQL queries over REST:
http://graphql.org/learn/serving-over-http/
{
"query": "...",
"operationName": "...",
"variables": { "myVariable": "someValue", ... }
}

Related

Get data from Google Ads API using App Script

I wanna get out campaigns reports using Google Rest API and it does'nt work in Google ads Apps script.
My code:
function main() {
const API_VERSION = "12";
const CUSTOMER_ID = "***"; //contais real custommer ID
const DEVELOPER_TOKEN = "***"; //contais real developper ID
const MANAGER_CUSTOMER_ID = "***"; //contais real manager ID
const OAUTH2_ACCESS_TOKEN = ""; //contais real ACCES TOKEN
const data = {
"pageSize": 10000,
"query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'"
};
const url = `https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
body: JSON.stringify(data),
"muteHttpExceptions": true
};
Logger.log(UrlFetchApp.fetch(url, options));
}
Result error:
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.ads.googleads.v12.errors.GoogleAdsFailure",
"errors": [
{
"errorCode": {
"queryError": "UNEXPECTED_END_OF_QUERY"
},
"message": "Error in query: unexpected end of query."
}
],
"requestId": "zKBR9-dJoG9NWAx3iJea2g"
}
]
}
}
But query is valid https://developers.google.com/google-ads/api/fields/v11/query_validator
enter image description here
Could you plese help?
Thanks
I wanna get out campaigns reports using Google Rest API and it does'nt work. My code and result is above.
Based on the documentation of UrlFetchApp, 'body' is not the correct option for passing in the query. You want 'payload'.
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
payload: JSON.stringify(data),
"muteHttpExceptions": true
};

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\""

How to pass javascript variable to graphql query?

I have a super simple GraphQl query, but im having trouble to make the query dynamic based on input. Lets say you will get a string in javascript that you want to pass along to the query, how is it done? Take example below, how would i replace the hardcoded string of "3111" on the Sku field in the product but instead inserting the value from the variable myString? I am just getting errors when i try to pass it along.
let myString = "3111"
`query getProductBySku {
site {
product(sku: "3111") {
id
entityId
name
sku
}
}
}`
Have a look here: https://graphql.org/graphql-js/passing-arguments/
In your case scenario:
var query = `query getProductBySku($sku: String) {
site {
product(sku: $sku) {
id
entityId
name
sku
}
}
}
`;
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables: { "3111" }, // this refers to SKU
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
Basically other than creating a query that allows argument to pass, you need a POST request with the body setup to accomodate the inputs which are expected to be fulfilled

Fetch(): Request body malformed

I want to make a fetch request to an API that accepts different types of body requests: twitter handle, facebook link, phone number, etc. The structure of the body is:
body: {
"typeOfHandle": "input"
}
Since there are different types of handles, I test the input type and assign it to the body accordingly, as seen below:
// handle is the input
let atSign = /^[#]/,
handleIsTwitter = atSign.test(handle.value),
handleType;
handleIsTwitter ? handleType = `"` + "twitter" + `"` : console.log("not twitter");
let abc = `"` + handle.value + `"`;
let bodyOfFetch = `{${handleType}: ${abc}}`;
console.log("body: " + bodyOfFetch);
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: JSON.stringify(bodyOfFetch)
})
.then(function(res) {
return res.json();
})
.then(function(json) {
console.log(json);
});
However, this method returns a body malformed error. When I do the request statically (i.e. replace the variables with static text, e.g. "twitter": "#alex") it works. I double-triple-quadruple checked the syntax, I don't think that is the problem. Can it be an issue on the API's side?
In your example bodyOfFetch is a string ({"twitter": "#alex"}). Either you can send it directly, this is:
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: bodyOfFetch
})
Or you can send a stringify object:
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: JSON.stringify({[handleType]: abc})
})
But sending JSON.stringify(bodyOfFetch) will stringify a json string, this will add surrounding " and escape existing quotation marks: "{\\"twitter\\": \\"#alex\\"}"
Hope this helps.

Code by Zapier Get Unexpected Token When Inserting InputData variable into JSON string

Have been trying to insert inputdata.SKU into the payload below. However, I get Unexpected Token error.
Complete Javascript code used in the Code by Zapier input box is below. Note have replaced the token with XXXXXXX in endpoint variable for security reasons.
var endpoint = 'https://api.yotpo.com/apps/XXXXXX/purchases/';
var payload = {
"validate_data": true,
"platform": "general",
"utoken": inputData.ACCESS_TOKEN,
"email": inputData.EMAIL,
"customer_name": inputData.CUST_NAME,
"order_id": inputData.ORDER_ID,
"order_date": inputData.ORDER_DATE,
"currency_iso": "NZD",
"products": {
inputData.SKU : {
"url": inputData.URL,
"name": inputData.NAME,
"image": inputData.IMAGE_URL
}
}
};
fetch(endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
}).then(function(response) {
return response.text();
}).then(function(responsebody) {
var output = {response: responsebody};
callback(null, output);
}).catch(function(error) {
callback(error);
});
It looks like you're using an expression, inputData.SKU, as a property name (key). Luckily, Zapier runs on node.js v4.3.2, so computed property names are supported.
Try changing that line to this (wrap the expression in brackets):
[inputData.SKU] : {

Categories

Resources