How to fetch Sleep data from Google's REST api? - javascript

I'm trying to fetch my sleep data from Google-Fit.
When I make the following request -
const { data: sleepData } = await axios({
method: 'POST',
url: 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate',
headers: {
Authorization: `Bearer ${accessToken}`,
},
data: {
aggregateBy: [{ dataTypeName: 'com.google.sleep.segment' }],
bucketByTime: { durationMillis: 86400000 },
startTimeMillis: startTimeQuery, // day start time in UNIX
endTimeMillis: endTimeQuery, // day end time in UNIX
},
});
I'm getting the following data with empty points -
{
"bucket": [
{
"startTimeMillis": "1651115600000",
"endTimeMillis": "1651202000000",
"dataset": [
{
"dataSourceId": "derived:com.google.sleep.segment:com.google.android.gms:merged",
"point": []
}
]
},
{
"startTimeMillis": "1651202000000",
"endTimeMillis": "1651288400000",
"dataset": [
{
"dataSourceId": "derived:com.google.sleep.segment:com.google.android.gms:merged",
"point": []
}
]
},
]}
Has anyone run into similar problems?
I'm using Google-Fit on an Android Device.

Hey here is a working example from Google Fitness REST API with my account which is connected to my sleep tracking device.
var axios = require('axios');
var data = JSON.stringify({
"aggregateBy": [
{
"dataTypeName": "com.google.sleep.segment"
}
],
"endTimeMillis": {endTimeMillis},
"startTimeMillis": {startTimeMillis}
});
var config = {
method: 'post',
url: 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate',
headers: {
'Authorization': 'Bearer {AccessToken}',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
The Only difference is to remove the bucketByTime so that Fitness API will send the segment points as small as possible.

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

Try to execute js script in manifest to ask privatte API with post request

I try to use js script in my jps to test credentials with a personal APi. The idea is to return an error code in the jps if credentials are false. In my computer my js script works fine but when i try to start my jps with this i have an javascript error.
my jps:
onInstall:
- script [*]: https://github.com/user/project/blob/master/script.js
responses:
401:
type: error
message: bad credentials
My js script:
const https = require('https')
var name = "some-name"
var password = "some-password"```
const data = JSON.stringify({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
})
const options = {
hostname: 'mYapi.com',
port: 443,
path: 'mypath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
var req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res.statusCode)
return res.statusCode;
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
I get this error in the console :
ERROR: script.response: {"result":1704,"line":50,"response":null,"source":"hx-core","time":122,"error":"org.mozilla.javascript.EvaluatorException: syntax error"}
And i try a lot of differents script to do this post request ----> works in my computer ( api send result 201 if credentials are good and 401 if not ) , -----> doesn't work in jelastic manifest.
So please can you explain me how i can do a post request with json on my API in Jelastic manifest ( js call script ). I thank you in advance !
The code that is executed by the "script" action runs on the JVM therefore it allows you to connect and use Java libraries.
To implement a POST request and determine the status of the output code, you can use Commons HttpClient.
See below for an example.
type: install
name: HttpClient Post
onInstall:
- script: |
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
var client = new HttpClient();
var name = "some-name";
var password = "some-password";
var requestEntity = new StringRequestEntity(toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
}), "application/json", "UTF-8");
var post = new PostMethod("https://example.com/");
post.setRequestEntity(requestEntity);
var status = client.executeMethod(post);
post.releaseConnection();
if (status == HttpStatus.SC_CREATED) { // 201
return { type : "success" };
} else if (status == HttpStatus.SC_UNAUTHORIZED) { // 401
return { type: "error", message: "bad credentials" };
}
return { type: "error", message: "unknown error" };
Also, you can find many useful examples and information in the Jelastic JPS Collection repository.
Perhaps the next script will be useful for you:
https://github.com/jelastic-jps/git-push-deploy/blob/master/scripts/add-web-hook.cs
One last thing that if you don't need the exact HTTP Status, you can use an integrated "Transport" class.
import com.hivext.api.core.utils.Transport;
var name = "some-name";
var password = "some-password";
var data = toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
});
try {
new Transport().post("https://example.com/", data, {
'Content-Type': 'application/json',
'Content-Length': data.length
});
return { type: "success" };
} catch (e) {
return {
type: "error",
message: "unknown error: " + e
};
}

How to get data form airhob api ? My request is giving me a 401

I want to get flight informations from an Api called airhob(https://www.airhob.com/developers/api/docs).
To do that I´m using ReactJS and Axios to fetch data.
In the Api documentation, the header is only:
apikey – Your sandbox or production API key
mode - sandbox or production
Content-Type - application/json
So to do that, I write the following code :
var authOptions = {
method: 'post',
url: 'https://dev-sandbox-api.airhob.com/sandboxapi/flights/v1.3/search',
headers: {
'Content-Type' : 'application/json',
'apikey': 'MyApiKey',
'mode' : 'sandbox'
},
data:{
"TripType": "O",
"NoOfAdults": 1,
"NoOfChilds": 0,
"NoOfInfants": 0,
"ClassType": "Economy",
"OriginDestination": [
{ "Origin": "SFO",
"Destination": "LAX",
"TravelDate": "04/23/2018" }
],
"Currency": "USD"
},
json: true
};
return axios(authOptions)
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
So the result for this code should display all flight to Los Angeles in my console.

axios GET data appearing as [undefined, undefined] in div

I'm trying to render a url's JSON data in the browser, but it's appearing in the div as undefined, undefined. When I put its response in console.log the object and its data appears, so there's some sort of disconnect between it appearing in the console and the browser. I've gotten the rest of my data (other REST calls) to appear, but until I fix this problem I won't be able to see them and continue with my project.
Any thoughts on this? I've been struggling with getting this data for a while and it's been bugging me.
PS - Not sure if it helps, but I'm using IE11 with this one (not that I want to, but I have little say in the matter).
index.js:
import axios from 'axios';
import officeComponent from './SiteAssets/scripts/office.js' // --- trying to put data here
import mattsComponent from './SiteAssets/scripts/matt.js'
import bioComponent from './SiteAssets/scripts/bio.js'
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
});
axios.all([
// Firm Directory
axios.get(__[redacted].[redacted] + "/[redacted]/Odata/Odata.ashx/HSJS20FirmDirectory?hsf=#UserName=" + queryDict.uname + "&$select=PreferredName,...otherinfo...,SPID", {
withCredentials: true,
headers: {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json"
}
}),
... // ---------- other GET requests
]).then(axios.spread((firm, bio, edu) => { // params order is important (firmData, bioData, etc. must follow that order)
let firmData = firm.data.d.results[0];
let bioData = bio.data.d.results[0];
// Office Info (relies on Firm Directory (firmData) SPID)
axios.get(__[redacted].[redacted] + "/[redacted]/Odata/Odata.ashx/OFM_Resources?$select=FloorMap,FloorMapID,ResourceLocation,Office,OfficeID,Office_Number&hsf=#ResourceType=Person%20AND%20User_Link_ID=" + firmData.spid + "&hso=OfficeID", {
withCredentials: true,
headers: {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json"
}
})
.then(function(response) {
let oComp = new officeComponent(response.data.d.results);
oComp.loadOfficeData(response.data.d.results);
console.log('oComp', response.data.d.results); // --------- shows the object tree with all of the JSON data
}).catch(function(err) {
console.log(err);
}),
// Matts Info (relies on Bio TK number)
axios.get(__[redacted].[redacted] + "/[redacted]/Odata/Odata.ashx/MattsTeams?hsf=#MattStatus=active,pending%20AND%20TkNumber=%27" + bioData.number + "%27", {
withCredentials: true,
headers: {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json"
}
}).then(function(response) {
let mComp = new mattsComponent(response.data.d.results);
mComp.loadMattsData(response.data.d.results);
}).catch(function(err) {
console.log(err);
})
let bComp = new bioComponent();
bComp.loadBioData(bioData);
bComp.loadEduData(eduData);
office.js:
import $ from 'jquery';
// ------------------- //
console.log("office.js working")
export default class {
constructor() {
}
loadOfficeData(response) {
$("#seat-val").append(response.office_number + ", " + response.floormap);
}
}
Office Data JSON:
{
"d": {
"results": [
{
"floormap": "[location here]",
"floormapid": 10,
"resourcelocation": "[redacted]",
"office": "[location here]",
"officeid": 3,
"office_number": "00-605"
}
]
}
}
Looks like results is an array, so you must access it as:
response[0].office_number
and
response[0].floormap

Graphql query with $http.post does not work

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", ... }
}

Categories

Resources