Search code examples
javascriptgoogle-apigoogle-oauthgoogle-analytics-apigoogle-api-js-client

API realtime Google analytics is not working on client side with js


enter image description here

I have tried use API key, and OAuth 2.0.

As result I have this error: http://prntscr.com/lov2pz

Which API key should I use? What mistakes have I made?

<script>

    function start() {
        // 2. Initialize the JavaScript client library.
        gapi.client.init({
            'apiKey': 'XXXXXX',
            // clientId and scope are optional if auth is not required.

        }).then(function() {

            return gapi.client.request({
                'path': 'https://www.googleapis.com/analytics/v3/data/realtime?ids=ga%3A185730557&metrics=rt%3AactiveUsers&fields=totalsForAllResults',
            })
        }).then(function(response) {
            console.log(response.result);
        }, function(reason) {
            console.dir(reason);

            console.log('Error: ' + reason.result.error.message);
        });
    };
    gapi.load('client', start);

</script>

Solution

  • First you need to understand the diffrence between private and public data. Public data is data that is not owned by anyone. Anyone can search for YouTube videos in the Youtube api for example

    Google analytics data on the other hand is private it is owned by a user. Api keys are used to access public data not private data. In order to access private google analytics data you will need to be logged in as a user who has access to that data.

    The tutorial quickstart js Will show you how to access google anlaytics data using JS you will have to alter it for the realtime api i am not a js developer so cant help with that but you should be able to understand the login process using this sample

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Hello Analytics Reporting API V4</title>
      <meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
      <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
    </head>
    <body>
    
    <h1>Hello Analytics Reporting API V4</h1>
    
    <!-- The Sign-in button. This will run `queryReports()` on success. -->
    <p class="g-signin2" data-onsuccess="queryReports"></p>
    
    <!-- The API response will be printed here. -->
    <textarea cols="80" rows="20" id="query-output"></textarea>
    
    <script>
      // Replace with your view ID.
      var VIEW_ID = '<REPLACE_WITH_VIEW_ID>';
    
      // Query the API and print the results to the page.
      function queryReports() {
        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(displayResults, console.error.bind(console));
      }
    
      function displayResults(response) {
        var formattedJson = JSON.stringify(response.result, null, 2);
        document.getElementById('query-output').value = formattedJson;
      }
    </script>
    
    <!-- Load the JavaScript API client and Sign-in library. -->
    <script src="https://apis.google.com/js/client:platform.js"></script>
    
    </body>
    </html>