Hello Analytics Reporting API v4; PHP quickstart for service accounts

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.

Create credentials

  1. Open the Service accounts page. If prompted, select a project.
  2. Click Create Service Account, enter a name and description for the service account. You can use the default service account ID, or choose a different, unique one. When done click Create.
  3. The Service account permissions (optional) section that follows is not required. Click Continue.
  4. On the Grant users access to this service account screen, scroll down to the Create key section. Click Create key.
  5. In the side panel that appears, select the format for your key: JSON is recommended.
  6. Click Create. Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. For information on how to store it securely, see Managing service account keys.
  7. Click Close on the Private key saved to your computer dialog, then click Done to return to the table of your service accounts.

Add service account to the Google Analytics account

The newly created service account will have an email address that looks similar to:


Use this email address to add a user to the Google analytics view you want to access via the API. For this tutorial only Read & Analyze permissions are needed.

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 a single file named HelloAnalytics.php, which will contain the sample code below.

  • Copy or download the following source code to HelloAnalytics.php.
  • Move the previously downloaded service-account-credentials.json to the same directory as the sample code.
  • 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';

$analytics = initializeAnalytics();
$response = getReport($analytics);

 * Initializes an Analytics Reporting API V4 service object.
 * @return An authorized Analytics Reporting API V4 service object.
function initializeAnalytics()

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $analytics = new Google_Service_AnalyticsReporting($client);

  return $analytics;

 * 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");

4. Run the sample

Run the sample using:

php HelloAnalytics.php

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