Not a valid json request, from DolphinDB JSON API - json

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)

Related

Google app scrips Slack API Get pins:list

Using Google app script as serverless for a slack bot. Having an issue returning specific values from slack API. I'm using the pins:list call. I am able to get the JSON in response and items calls but get null when trying to get the next set of values. I am looking to return "permalinks" so I can then post back into slack what items are pinned to a room. here is my script:(without giving away company details)
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"}}
var response = UrlFetchApp.fetch(url, options)
var json = response.getContentText();
var data = JSON.parse(json);
var items = data.item.permalinks;
Logger.log(items);
}
Thank you!!
SUGGESTION
Upon reviewing Slack's official docs for pins.list method, I suppose that this sample JSON response below is the same as the actual JSON response that you're getting:
Sample JSON response:
{
"items": [
{
"channel": "C2U86NC6H",
"created": 1508881078,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151",
"pinned_to": [
"C2U86NC6H"
],
"text": "What is the meaning of life?",
"ts": "1508197641.000151",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
},
{
"channel": "C2U86NC6H",
"created": 1508880991,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015",
"pinned_to": [
"C2U86NC6H"
],
"text": "The meaning of life, the universe, and everything is 42.",
"ts": "1503289197.000015",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
}
],
"ok": true
}
You can try iterating though the items array via looping in the JSON response to get each permalinks data, as seen on this quick test below:
Quick Test
function GetPinns() {
//This sample JSON String response was from https://api.slack.com/methods/pins.list#examples
var json =
"{\"items\": [{\"channel\": \"C2U86NC6H\",\"created\": 1508881078,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"What is the meaning of life?\",\"ts\": \"1508197641.000151\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"},{\"channel\": \"C2U86NC6H\",\"created\": 1508880991,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"The meaning of life, the universe, and everything is 42.\",\"ts\": \"1503289197.000015\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"}],\"ok\": true}";
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Result
Your script will look like this:
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"
}
}
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Reference
https://www.sitepoint.com/loop-through-json-response-javascript/
Thank you!!
I wound up with this in the end
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response.getContentText());
var items = json.items
var linkList = ""
for(var x in items) {
var link = items[x]["message"]["permalink"]
var text = items[x]["message"]["text"]
linkList += "<" + link +"|" + text +">" + "\n"
}

How to Retrieve (not create) Tasks from Asana using Apps Script & Personal Access Token

I am attempting to retrieve, but not create, tasks from Asana using Google Apps Script.
Using the Asana API Explore, I have constructed a URL that returns the data I desire: https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=987654321987654&completed_since=2018-02-22&limit=100&workspace=456789123456
This URL returns the desired data, in the following format:
{
"data": [
{
"id": 147258369147258,
"assignee_status": "inbox",
"name": "An example task name"
},
{
"id": 963852741963852,
"assignee_status": "upcoming",
"name": "And second example task name."
},
//etc...
]
}
With that URL as a model, I have created a Personal Access Token and executed the following function within Apps Script:
function getTasks5() {
// Asana Personal Token
var bearerToken = "Bearer " + "asdf123456789asdf456789456asdf";
//Request
var request = {
data: {
opt_fields: ["name", "assignee_status"],
assignee: "987654321987654",
completed_since: "2018-02-22",
limit: "100",
workspace: "456789123456"
}
};
// Request options
var options = {
method: "GET",
headers: {
"Authorization": bearerToken
},
contentType: "application/json",
payload: JSON.stringify(request)
};
var url = "https://app.asana.com/api/1.0/tasks";
var result = UrlFetchApp.fetch(url, options);
var reqReturn = result.getContentText();
Logger.log(reqReturn);
}
Instead of returning the desired data as the aforementioned URL does, the function creates an unnamed task in Asana, which is undesirable. It also returns this response containing undesired data:
{
"data": {
"id": 123456789123456,
"created_at": "2018-02-22T20:59:49.642Z",
"modified_at": "2018-02-22T20:59:49.642Z",
"name": "",
"notes": "",
"assignee": {
"id": 987654321987654,
"name": "My Name Here"
},
"completed": false,
"assignee_status": "inbox",
"completed_at": null,
"due_on": null,
"due_at": null,
"projects": [],
"memberships": [],
"tags": [],
"workspace": {
"id": 456789123456,
"name": "Group Name Here"
},
"num_hearts": 0,
"num_likes": 0,
"parent": null,
"hearted": false,
"hearts": [],
"followers": [
{
"id": 987654321987654,
"name": "My Name Here"
}
],
"liked": false,
"likes": []
}
}
Is it possible to simply GET a list of tasks in the manner exemplified by my first JSON example above without creating a task, and without resorting to using OAuth? If so, what changes to the Apps Script function need to be made?
Alright, the problem was with the approach I was taking. Rather than format the request with a payload (which infers a POST request), I needed to structure it more traditionally as a GET request, like so:
var requestUrl = "https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=123456789123&completed_since=2018-02-22&limit=100&workspace=987654321987";
var headers = {
"Authorization" : "Bearer " + AUTH_TOKEN
};
var reqParams = {
method : "GET",
headers : headers,
muteHttpExceptions: true
};
Then I was able to perform:
UrlFetchApp.fetch(requestUrl, reqParams);
And obtain the data I was after.

Ajax post request to google NLP

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.

How to display specific information from JSON API?

How can i display the value of a specific variable stored in an JSON API array?
For e.g. how could i display the current Bitcoin price in USD in a specific wordpress post using coinmarketcaps JSON API (https://api.coinmarketcap.com/v1/ticker/bitcoin/)?
The API gives me the following output:
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "3351.98",
"price_btc": "1.0",
"24h_volume_usd": "1455740000.0",
"market_cap_usd": "55289274334.0",
"available_supply": "16494512.0",
"total_supply": "16494512.0",
"percent_change_1h": "0.55",
"percent_change_24h": "3.45",
"percent_change_7d": "17.52",
"last_updated": "1502145551"
}
]
I only need to display the value of "price_usd" tho.
I've tried to do it this way, but it didn't work:
<script>
var btcPrice;
function UpdateBtcPrice(){
$.ajax({
type: "GET",
url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/",
dataType: "json",
success: function(result){
btcPrice = result[0].price_usd;
},
error: function(err){
console.log(err);
}
});
}
</script>
Any help would be much appreciated!
You need to call the function to execute the request:
var btcPrice;
function UpdateBtcPrice(){
$.ajax({
type: "GET",
url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/",
dataType: "json",
success: function(result){
btcPrice = result[0].price_usd;
},
error: function(err){
console.log(err);
}
});
}
UpdateBtcPrice();
You can try this code
<?php
//get data with api call
$response = file_get_contents('https://api.coinmarketcap.com/v1/ticker/bitcoin/');
$response = json_decode($response);
echo $response[0]->price_usd;//print the value
?>

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
};