javascriptgoogle-apigoogle-fitgoogle-fit-sdk

Google fit aggregate rest api call issue parse error javascript


I am calling the google fit rest api as following

 const requestBody ={
    "aggregateBy": [{
      "dataTypeName": "com.google.step_count.delta",
      "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
    }],
    "bucketByTime": { "durationMillis": 86400000 },
    "startTimeMillis": 1561228200000,
    "endTimeMillis": 1561652514300
    }

const userAction = async () => {
    const response = await fetch('https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate', {
      method: 'POST',
      body: requestBody, 
      headers: {
      'Content-Type': 'application/json',
      'Content-Length': '302',
      'Authorization': 'Bearer ' + authcode,
      }
    });
    const jsonResponse = await response.json();
    console.log(jsonResponse);
  }
  userAction();

I am getting response as

{ "error": { "errors": [{ "domain": "global", "reason": "parseError", "message": "Parse Error" }], "code": 400, "message": "Parse Error" } }

Not sure where the parsing error is happening. Any help pointing to where it occours will be much appreciated. Note - auth token is taken correctly, so it probably cant be the issue. Also I am running on local host.


Solution

  • Got it to work by the following code(I have hardcoded static params). Add api key and client ID and run it would work. This link helped - https://developers.google.com/fit/rest/v1/reference/users/dataset/aggregate.

    <script>
    
      function authenticate() {
        return gapi.auth2.getAuthInstance()
            .signIn({scope: "https://www.googleapis.com/auth/fitness.activity.read"})
            .then(function() { console.log("Sign-in successful"); },
                  function(err) { console.error("Error signing in", err); });
      }
      function loadClient() {
        gapi.client.setApiKey("YOUR APP ID");
        return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/fitness/v1/rest")
            .then(function() { console.log("GAPI client loaded for API"); },
                  function(err) { console.error("Error loading GAPI client for API", err); });
      }
      // Make sure the client is loaded and sign-in is complete before calling this method.
      function execute() {
        return gapi.client.fitness.users.dataset.aggregate({
          "userId": "me",
          "resource": {
            "aggregateBy": [
              {
                "dataTypeName": "com.google.step_count.delta",
                "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
              }
            ],
            "endTimeMillis": 1561652514300,// Any time in milliseconds
            "startTimeMillis": 1561228200000,// Any time in milliseconds
            "bucketByTime": {
              "durationMillis": 86400000// Any duration in milliseconds
            }
          }
        })
            .then(function(response) {
                    // Handle the results here (response.result has the parsed body).
                    console.log("Response", response);
                  },
                  function(err) { console.error("Execute error", err); });
      }
      gapi.load("client:auth2", function() {
        gapi.auth2.init({client_id: "YOUR CLIENT ID"});
      });
    </script>
    <button onclick="authenticate().then(loadClient)">authorize and load</button>
    <button onclick="execute()">execute</button>