1
votes

I'm new to using this API, and I am struggling with retrieving my data using Google Analytics Reporting API v4. I am only attempting to retrieve the analytics for a website so I can build a dashboard. I am following the example here: Hello Analytics Reporting API v4; JavaScript quick start for web applications

I am able to make a request, however, I keep getting a 400 error that is might be this: 400: Invalid Credentials

`Invalid JSON payload received. Unknown name "express" at 'report_requests[0].metrics[0]': Cannot find field.
handleError @ Test.js:64
h.o0 @ cb=gapi.loaded_0:53
xs @ cb=gapi.loaded_0:56
Wq @ cb=gapi.loaded_0:56
_.C.uea @ cb=gapi.loaded_0:55
Ap @ cb=gapi.loaded_0:49`

I have no idea what I am doing wrong, and I am hoping someone can point me in the right direction.

This is a react application. I am making the request after the component mounts.

import React, { Component } from 'react';
import GoogleLogin from 'react-google-login';
import $ from 'jquery';

const VIEW_ID = '17414592';
const CLIENT_ID = "936270024581-stgn130l17v21s6vjch9p751hiqbovac.apps.googleusercontent.com";
const DISC_DOCS = 'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ express: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}

What am I doing wrong? How can I properly do a batchRequest to retrieve all data from 7 days using Google Analytics Reporting APIv4? I feel as though I am using all required fields, however, I do not know what I am missing. Can you point me in the right direction?

2

2 Answers

2
votes

I'm answering my own question in case anyone else needs help using google analytics reporting api v4 with react. This is what I needed to do in order to construct a gapi button that would then make a basic request. The error I was creating was from a typo. Instead of metrics:[{expression: 'ga:sessions'}] I was using metrics:[{express: 'ga:sessions'}].

Here is a component that will create a simple request. Please note you have to change the VIEW_ID to your value.

import React, { Component } from 'react';
import $ from 'jquery';

const VIEW_ID = '17414592';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ expression: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}
1
votes

401: Invalid Credentials Invalid authorization header. The access token you're using is either expired or invalid.

This basically means that you need to sign in again.

Click the Sign in button, and authorize access to Google Analytics.

Remember access tokens are only valid for an hour your going to have to sign it in again when ever it expires.