How to pass the request object as query string in Power Query Formula Language - api

I am trying to pull data from an API in power bi using power query formula language.
My code is:
let
obj= "{ ""dataset"": ""mydataset"",""queries"": [ { ""type"": ""single_measurement"", ""measure"": { ""aggregator"": ""unique_count"", ""column"": ""visitor_id"" } } ], ""start"":1451638800000,""end"":1468430640000,""max_groups"":1000,""group_by"":[""extrhike""]}",
authKey = "Token js+JG/FaGiZcFZPVAsAXmN+d20000",
url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query?query=obj",
GetJson = Json.Document(Web.Contents(url,[Headers = [#"Authorization"=authKey, #"Content-Type"="application/json"]]))
in
GetJson
I want to pass the data request object(obj) as a query string like following
https://myhostaddress.cloudapp.azure.com/api/v1/query?query={ "dataset": "mydataset","queries": [ { "type": "single_measurement", "measure": { "aggregator": "unique_count", "column": "visitor_id" } } ], "start":1451638800000,"end":1468430640000,"max_groups":1000,"group_by":["extrhike"]}
I am unable to pass obj as a querystring value in power query.I am getting following error
DataFormat.Error: Invalid URI: The hostname could not be parsed.
Details:
https:// myhostaddress.cloudapp.azure.com/api/v1/query?query=obj
How do I pass the request object(obj) as query string in Power Query Formula Language.
Thanks in advance

Have you tried passing in your query parameters with the Query argument of Web.Contents ?
For e.g
let
Url = "https:// myhostaddress.cloudapp.azure.com"
Request = Json.Document(Web.Contents(url,
[Headers =
[#"Authorization"=authKey,
#"Content-Type"="application/json"],
RelativePath = "/api/v1/query",
Query = [
<insert record here of your query object>
]
]
An example of the Query record might be:
Query = [#"Argument 1" = "Foo", #"Argument 2" = "Bar", limit = "1000", skip="500"]
You can read about the options here: https://msdn.microsoft.com/en-us/library/mt260892.aspx

You need to add the strings together. It should be url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query?query=" & obj,.

Try to use this
It POSTs content instead of GETting query
let
obj = "{ ""dataset"": ""mydataset"",""queries"": [ { ""type"": ""single_measurement"", ""measure"": { ""aggregator"": ""unique_count"", ""column"": ""visitor_id"" } } ], ""start"":1451638800000,""end"":1468430640000,""max_groups"":1000,""group_by"":[""extrhike""]}",
authKey = "Token js+JG/FaGiZcFZPVAsAXmN+d20000",
url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query",
GetJson = Json.Document(Web.Contents(url,[
Headers = [#"Authorization"=authKey, #"Content-Type"="application/json"],
Content = Text.ToBinary(obj)
]))
in
GetJson

You also may use this
It escapes obj to percent-string and appends to "query" parameter
let
obj= "{ ""dataset"": ""mydataset"",""queries"": [ { ""type"": ""single_measurement"", ""measure"": { ""aggregator"": ""unique_count"", ""column"": ""visitor_id"" } } ], ""start"":1451638800000,""end"":1468430640000,""max_groups"":1000,""group_by"":[""extrhike""]}",
authKey = "Token js+JG/FaGiZcFZPVAsAXmN+d20000",
url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query?query="&Uri.EscapeDataString(obj),
GetJson = Json.Document(Web.Contents(url,[Headers = [#"Authorization"=authKey, #"Content-Type"="application/json"]]))
in
GetJson

Related

How to set formatting with Google sheets API for python?

In theory this was answered in Remove only formatting on a cell range selection with google spreadsheet API but for the life of me I cannot get it to work.
I want to write a function that clears the formatting of a given Google Sheet. Here is what I think is the right way to do it based on the above:
def clear_sheet_formatting():
spreadsheetID = "1pQoBG0q6f0Ni6yMiC9BSIXVLGMmvBRc07pGXqMA2VtA"
global service_spreadsheets
open_connection()
body = {
"requests": [
{
"updateCells": {
"range": {
"sheetId": "Sheet1",
},
"fields": "userEnteredFormat"
}
}
]
}
func = lambda: service_spreadsheets.batchUpdate(spreadsheetId=spreadsheetID,
body=body).execute()
result = execute_query(func)
The sheet itself is very boring:
But I am getting the following error:
WARNING:root:Google API call failed with the following error, sleeping 20 seconds: Invalid value at 'requests[0].update_cells.range.sheet_id' (TYPE_INT32), "Sheet1"
What am I doing wrong? How do I make this work?
I perform a test regarding this, use this sample code to see if that helps.
I'm currently using this scopes:
SCOPES = ['https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/spreadsheets' ]
And the sample code I'm using is:
try:
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API and the sheet ID for "Sheet1"
# the ID is not the name of the sheet but a number.
call_sheet_with_format = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute()
sheets_with_format = call_sheet_with_format.get('sheets', '')
sheet_id = sheets_with_format[0].get("properties", {}).get("sheetId", 0)
request_body = {
'requests': [
{
'updateCells': {
'range': {
'sheetId': sheet_id
},
'fields':'userEnteredFormat'
}
}
]
}
request = service.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=request_body)
response = request.execute()
except HttpError as err:
print(err)
Or you can get the sheetId directly in the Google Sheet:
And remove this part of the
sheets_with_format = call_sheet_with_format.get('sheets', '')
sheet_id = sheets_with_format[0].get("properties", {}).get("sheetId", 0)

json path for response - API Restassured

Below is the response i get for post call.
How to get quoteId and fee amount value using Json from the below response.
{
"data": {
"quoteId": "Lid123",
"loanTerm": "48.0",
"lenderRate": "4.5",
"customerRate": "4.499999999999904",
"fees": [
{
"feeType": "EstablishmentFee",
"feeAmount": "450"
}
],
"periodPaymentInclGSTAmount": "6416.5"
}
}
Thank you in advance
You can use jsonpath() method to extract value from json.
Response res = ...
String quoteId = res.jsonPath().getString("data.quoteId");
String feeAmount = res.jsonPath().getString("data.fees[0].feeAmount");
System.out.println(quoteId); //Lid123
System.out.println(feeAmount); //450
String id = JsonPath.from(reponseBody).getString("data.quoteId");
String EstablishmentFee = JsonPath.from(reponseBody).getString("data.fees.feeAmount");

Read Google Spreadsheets conditonal format information

I wish to read google spreadsheets conditional format information with script. I do it as below:
function readConditionalFormatInfo() {
var url = "https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId?fields=sheets(properties(title,sheetId),conditionalFormats)"
var response = UrlFetchApp.fetch(url)
Logger.log(response)
}
But error happen:
Request failed for https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId?fields=sheets(properties(title,sheetId),conditionalFormats) returned code 403. Truncated server response: { "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } } (use muteHttpExceptions option to examine full response) (line 214, file "Code")
Maybe I should not run REST API in GAS but I don't know how to do it in script!
Appreciate if anyone can help!
Something like below:
function readConditionalFormat() {
var sheet = SpreadsheetApp.getActive().getActiveSheet();
var rules = sheet.getConditionalFormatRules();
if (rules != null) {
for (var i=0;i<rules.length;i++) {
var rule = rules[i].getBooleanCondition()
var criteria = rule.getCriteriaType()
var value = rule.getCriteriaValues()
var bakcolor = rule.getBackground()
Logger.log(criteria+ " -> " + value + ":" + bakcolor);
}
} else {
Logger.log('Conditional Format rule null')
}
}

Display dynamic data with JSON API Jquery

I've been reading about Javascript for 2 days now and I'm still confused. I'm familiar with HTML and CSS. My goal is to display a dynamic value on my website. The data will be from an API call using JSON.
The URL i'm using displays info like this
{
"error" : 0,
"error_message" : "-",
"amount" : 35.63000
}
What I want to do is take the "amount" variable and display it on my website. So far I have managed to jumble a bunch of code together that barely makes sense to me. I'm probably using all the wrong syntax so I will continue to try and figure this out myself. All this does it displays a static variable in "div1". What is the best way to convert the variable from the API call to show instead.
$.getJSON('https://www.amdoren.com/api/currency.php?api_key=jbqe5fH8AykJTFbnyR7Hf3d2n3KVQR&from=USD&to=THB&amount=1', function(data) {
//data is the JSON string
});
////
var $items = $('#amount')
var obj = {}
$items.each(function() {
obj[this.id] = $(this).val();
})
var json = JSON.stringify(obj);
///
var obj = [ {
"error": 0,
"error_message": "-",
"amount": 35.60000 ///THIS IS OBVIOUSLY STATIC...
}]
var tbl = $("<table/>").attr("id", "mytable");
$("#div1").append(tbl);
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td3 = "<td>" + obj[i]["amount"] + "</td></tr>";
$("#mytable").append(tr + td3);
}

Dynatree init from custom json data

There is an example on the website on how to construct child nodes from custom data:
$("#tree").dynatree({
[…]
onLazyRead: function(node){
$.ajax({
url: […],
success: function(data, textStatus){
// In this sample we assume that the server returns JSON like
// { "status": "...", "result": [ {...}, {...}, ...]}
if(data.status == "ok"){
// Convert the response to a native Dynatree JavaScipt object.
var list = data.result;
res = [];
for(var i=0, l=list.length; i<l; i++){
var e = list[i];
res.push({title: "" + i + ": " + e.fcurr + "-" + e.tcurr + ":" + e.ukurs,
icon: false});
}
// PWS status OK
node.setLazyNodeStatus(DTNodeStatus_Ok);
node.addChild(res);
}else{
// Server returned an error condition: set node status accordingly
node.setLazyNodeStatus(DTNodeStatus_Error, {
tooltip: data.faultDetails,
info: data.faultString
});
}
}
});
[…]
});
But there is no mention on how to do this for the initialization of the tree. I tried the following:
initAjax: {
type: "POST",
url: "/doSomething",
data: ...
contentType: "application/json; charset=utf-8"
success: function(data, textStatus){
// In this sample we assume that the server returns JSON like
// { "status": "...", "result": [ {...}, {...}, ...]}
if(data.status == "ok"){
// Convert the response to a native Dynatree JavaScipt object.
var list = data.result;
res = [];
for(var i=0, l=list.length; i<l; i++){
var e = list[i];
res.push({title: "" + i + ": " + e.fcurr + "-" + e.tcurr + ":" + e.ukurs,
icon: false});
}
// PWS status OK
node.setLazyNodeStatus(DTNodeStatus_Ok);
node.addChild(res);
}else{
// Server returned an error condition: set node status accordingly
node.setLazyNodeStatus(DTNodeStatus_Error, {
tooltip: data.faultDetails,
info: data.faultString
});
}
}
},
But then I get an error saying success doesn't work and to use some other method, but there is no documentation on how to use the other method? Can anyone help me out here? I tried using dataFilter to filter out my json string that is being returned, but that didn't work; I tried to use onPostInit and postProcess but don't know exactly what to do since there is no documentation: Do I return the data string after its been reformated, do I return the json version of the data? do I just do data = format(data)?
Any help would be greatly appreciated.
I will be having a lot of status codes and need to do different things based on the code; such as if I have code 1 it means I need to change the class of the node to have red text; or if I return code 2 it means there was an internal error and I need to add that to the node text; etc.