Hello Analytics Reporting API v4; PHP quickstart for web applications

This tutorial walks through the steps required to access the Analytics Reporting API v4.

1. Enable the API

To get started using Analytics Reporting API v4, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.

Note: To create a Web Client ID or an Installed Application Client, you need to set a product name in the consent screen. If you have not done so already you will be prompted to Configure consent screen.

Create credentials

  • Open the Credentials page.
  • Click Create credentials and select OAuth client ID
  • For the Application type select Web application.
  • Name the client ID quickstart and click Create.
  • Leave the Authorized JavaScript origins blank, it is not needed for this tutorial.
  • Set the Authorized redirect URIs to http://localhost:8080/oauth2callback.php
  • Click Create.

From the Credentials page click into the newly created client ID, and click Download JSON and save it as client_secrets.json; you will need it later in the tutorial.

2. Install the client library

You can obtain the Google APIs Client Library for PHP using Composer:

composer require google/apiclient:^2.0

3. Setup the sample

You'll need to create two files:

  • index.php will be the main page visited by the user.
  • oauth2callback.php will handle the OAuth 2.0 response


This file contains the main logic for querying the Google Analytics APIs and displaying the results.

  • Copy or download the first sample code to index.php.
  • Replace the value of VIEW_ID. You can use the Account Explorer to find a View ID.

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';


$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');

// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.

  // Create an authorized analytics service object.
  $analytics = new Google_Service_AnalyticsReporting($client);

  // Call the Analytics Reporting API V4.
  $response = getReport($analytics);

  // Print the response.

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

 * Queries the Analytics Reporting API V4.
 * @param service An authorized Analytics Reporting API V4 service object.
 * @return The Analytics Reporting API V4 response.
function getReport($analytics) {

  // Replace with your view ID, for example XXXX.

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );

 * Parses and prints the Analytics Reporting API V4 response.
 * @param An Analytics Reporting API V4 response.
function printResults($reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");

      for ($j = 0; $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];
          print($entry->getName() . ": " . $values[$k] . "\n");


This file handles the OAuth 2.0 response. Copy or download the second sample code to oauth2callback.php.


// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

4. Run the sample

Run the sample with a web server configured to serve PHP. If you use PHP 5.4 or newer, you can use PHP's built-in test web server by executing the following command:

php -S localhost:8080 -t /path/to/sample

Then visit http://localhost:8080 in your browser.

When you finish these steps, the sample outputs the number of sessions for the last seven days for the given view.