Ajax post request to google NLP - json

Im trying to do a post request to GCP Natural Language for sentiment analysis.
When I try the data format on the code explorer on google it works fine but when I run it on a html page I get an error that reads
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message."
},
{
"description": "Invalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message."
}
]
}
]
}
}
My code is:
<!DOCTYPE html>
<html>
<body>
<h1> Testing sentiment Analysis </h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var APIKEY = "AN API KEY";
$.ajax({
type : "POST",
url : "https://language.googleapis.com/v1/documents:analyzeSentiment?key="+APIKEY,
data : {
"document": {
"type": "PLAIN_TEXT",
"content": "Hello I am great"
},
"encodingType": "UTF8",
},
success: function(res) {
console.log(res);
alert(res['message']);
},
error: function(res) {
console.log(res['message']);
alert(res);
},
});
</script>
</body>
</html>

UPDATE:
A colleague has pointed me to the MISTAKE I was making. We have to use JSON.stringify() in order to send the request. The code should be like this:
$.ajax({
type : "POST",
url : "https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=YOUR-API-KEY",
contentType : "application/json; charset=utf-8",
data :
JSON.stringify({
"document": {
"type": "PLAIN_TEXT",
"language": "en",
"content": "Hola Victor"
},
"encodingType": "UTF8"}),
success : function(_result){
if (_result) {
alert('SUCCESS');
} else {
alert('ERROR');
}
},
error : function(_result){
}
});
I have tested it and it works.

Related

Nested JSON on WireMock Response

Is there any way to dynamically include JSON from the request body in the response?
Input Request
{
"id":"1234",
"message":"{\"key\":\"value\"}"
}
Expected Output
{
"status":"CREATED",
"id":"1234",
"message":"{\"key\":\"value\"}"
}
The message and id fields are dynamic and need to be picked from the request.
I have tried the below mapping to dynamically load the response from the request but \" inside message json is converted to "
{
"request": {
"method": "POST",
"urlPath": "/test"
},
"response": {
"status": 200,
"transformers": [
"response-template"
],
"jsonBody": {
"status": "CREATED",
"id": "{{jsonPath request.body '$.id'}}",
"message": "{{jsonPath request.body '$.message'}}"
}
}
}
This returns message as {"key":"value"}.
Even, I have tried changing the mapping to {{{jsonPath request.body '$.message'}}}. But this messes up the whole response json and message value is being returned as "{"key":"value"}" without escape characters.
I'm looking for suggestions to map message dynamically. Thanks in advance.

Not a valid json request, from DolphinDB JSON API

I'm trying the JSON API provided by DolphinDB, following this tutorial.
And I tried the code snippet like this:
var code = "1+2";
code = encodeURIComponent(code);
paramJson = {
"sessionID": "942605602",
"functionName": "executeCode",
"params": [{
"name": "script",
"form": "scalar",
"type": "string",
"value": code
}]
}
var option = {
url: "http://localhost:9920",
async: true,
data: paramJson,
type: "POST",
dataType: "json",
success: function (data) {
var resultJson = data;
console.log(data);
}
}
$.ajax(option);
Here is the log I got from chrome:
{sessionID: "800870454", userId: "", resultCode: "1", msg: "not a valid json request [sessionID=942605602&func…type%5D=string&params%5B0%5D%5Bvalue%5D=1%252B2].", object: Array(0)}msg: "not a valid json request [sessionID=942605602&functionName=executeCode&params%5B0%5D%5Bname%5D=script&params%5B0%5D%5Bform%5D=scalar&params%5B0%5D%5Btype%5D=string&params%5B0%5D%5Bvalue%5D=1%252B2]."object: []resultCode: "1"sessionID: "800870454"userId: ""__proto__: Object
It report not a valid json request, but I don't know what's wrong with my request.
You can try serializing JSON objects before sending requests
data = JSON.stringify(paramJson)

Use Apps Script URLFetchApp to access Google Datastore Data

I want to experiment with Google Datastore via Apps Script because I have a current solution based on Google sheets that runs into timeout issues inherent in constantly transacting with Drive files. I've created a test project in Google cloud with a service account and enabled library MZx5DzNPsYjVyZaR67xXJQai_d-phDA33
(cGoa) to handle the Oauth2 work. I followed the guide to start it up here and got all the pertinent confirmation that it works with my token (and that removing the token throws an 'authentication failed prompt').
Now I want to start with a basic query to display the one entity I already put in. I can use the API Explorer here and run this query body:
{
"query": {}
}
and get this result:
{
"batch": {
"entityResultType": "FULL",
"entityResults": [
{
"entity": {
"key": {
"partitionId": {
"projectId": "project-id-5200707333336492774"
},
"path": [
{
"kind": "Transaction",
"id": "5629499534213120"
}
]
},
"properties": {
"CommentIn": {
"stringValue": "My First Test Transaction"
},
"Status": {
"stringValue": "Closed"
},
"auditStatus": {
"stringValue": "Logged"
},
"User": {
"stringValue": "John Doe"
},
"Start": {
"timestampValue": "2017-08-17T18:07:04.681Z"
},
"CommentOut": {
"stringValue": "Done for today!"
},
"End": {
"timestampValue": "2017-08-17T20:07:38.058Z"
},
"Period": {
"stringValue": "08/16/2017-08/31/2017"
}
}
},
"cursor": "CkISPGogc35whh9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"version": "1503004124243000"
}
],
"endCursor": "CkISPGogc35wcm9qZWN0LWlkLTUyMDAxxDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"moreResults": "NO_MORE_RESULTS"
}
}
I try to do the same thing with this code:
function doGet(e)
{
var goa = cGoa.GoaApp.createGoa('Oauth2-Service-Account',
PropertiesService.getScriptProperties()).execute(e);
if(goa.hasToken()) {var token = goa.getToken();}
var payload = {"query":{}}
;
var result = UrlFetchApp.fetch('https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
method: "POST",
headers: {authorization: "Bearer " + goa.getToken()},
muteHttpExceptions : true,
payload: payload
});
Logger.log(result.getBlob().getDataAsString());
}
and get this error in the logger:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
If I try to use another word such as 'resource' or 'GqlQuery', I get this error:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message."
}
]
}
]
}
}
I can't tell from the API Documentation what my syntax is supposed to be. Can anyone tell me how to compile a functional request body from Apps Script to Datastore?
You need to set the contentType of your payload as well as stringify your JSON payload as follows:
var result = UrlFetchApp.fetch(
'https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
'method':'post',
'contentType':'application/json',
'headers': {authorization: "Bearer " + goa.getToken()},
'payload':JSON.stringify(payload)
}
);

google qpx query in Google script

i'm tryng to request a (simple) flight-query trough google flight service via Apps Script
this is my code
function myFunction() {
var api_key = "XXXXXXXXXXXXXXX";
var url2= "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key;
var param2 ={
"method" : "POST",
"contentType":"application/json",
"headers" : {"Content-Type": "application/json"
},
"request": {"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS","destination": "LAX","date": "2015-03-01"}]
},
muteHttpExceptions : true
};
try {
var response = UrlFetchApp.fetch(url2,param2);
Logger.log(response)
} catch (e) {
Logger.log(e)
}
}
this request send me error code
"error": {"errors": [{
"domain": "global",
"reason": "badRequest",
"message": "Invalid inputs: received empty request."
}
],
"code": 400,
"message": "Invalid inputs: received empty request."
}
The qpx Api is loaded in my developer console....anyone has any idea?
thanks in advance
Two things, the body of the request must be specified with the "payload" property, not "request", and you must actually convert your Javascript Object to a JSON string before posting it. (You also don't need the "headers" property, "contentType" will suffice, but I don't think it hurts anything)
var param2 ={
"method" : "post",
"contentType":"application/json",
"payload": JSON.stringify({"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2015-03-01"
}]
}
),
muteHttpExceptions : true
};
It's all documented here: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
However, the need to JSON.stringify() usually throws people off, if you pass a Javascript Object directly in the payload it is posted as form-encoded key/value pairs.
thanks very much...you put me in the right direction!
this is the right syntax:
var param2 ={
"method" : "post",
"contentType":"application/json",
"payload": JSON.stringify
(
{"request":
{"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2015-03-01"
}]
}
}
),
muteHttpExceptions : true
};

Insert post Blogger API failed in GAS

hi all iam trying insert post using GAS but failed.. can you tell me what im wrong... thx in advance....
here my code
`function sendHttpPost() {
var API_KEY = 'my api key';
var scope = "http://www.blogger.com/feeds/";
var oAuthConfig = UrlFetchApp.addOAuthService("blogger");
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "486683248036684073"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
var options =
{
"contentType":"application/json",
"oAuthServiceName" : "blogger",
"oAuthUseToken" : "always",
"method" : "POST",
"payload" : payload
};
var respon = UrlFetchApp.fetch("https://www.googleapis.com/blogger/v3/blogs/486683248036684073/posts?key="+API_KEY, options);
and here is error message
Request failed for returned code 400. Server response: { "error": {
"errors": [ { "domain": "global", "reason": "parseError", "message":
"Parse Error" } ], "code": 400, "message": "Parse Error" } }
I believe you are trying to use oauth1 when oauth2 is required.
there already is a unanswered request about that here.
Implementing oauth 2 with Google app script is really a pain, so I made an attempt to build a library that could answer the need (dioxygen library) - it work a little bit like the oauth2 playground but it's less pretty.
With a little work you should be able to adapt it to your need with blogger.
I tried Harold's library, but after successfully retrieving OAuth token, I ended up with the same error.
But, when I issued the same JSON request as in my script through the API Explorer, it was processed:
https://developers.google.com/blogger/docs/3.0/reference/posts/insert
[UPDATE]
I am taking it back. This code works. I just replaced the payload variable and put the JSON request straight into URL fetch options. So there was some problem with passing that payload variable into options variable.
function testBlogger() {
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "YOUR_BLOG_ID"
},
"title": "New post",
"content": "With content..."
};
var options =
{
"method" : "post",
"headers" : { "Authorization" : "Bearer YOUR_ACTIVE_TOKEN"},
"contentType" : "application/json",
"payload" : '{ "kind": "blogger#post", "blog": { "id": "YOUR_BLOG_ID" }, "title": "New post", "content": "With content..." }'
};
try {
var result = UrlFetchApp.fetch(
"https://www.googleapis.com/blogger/v3/blogs/YOUR_BLOG_ID/posts",
options);
Logger.log(result);
} catch (e) {
Logger.log(e);
}
}