API Quickstart using the command line

This page shows you how to get started with the Google Analytics Data API v1 using the command line.

Step 1. Enable the API

Click this button to create a new Cloud Platform project, automatically enable the Google Analytics Data API v1 and create the OAuth2 credentials needed for this tutorial:

Enable the Google Analytics Data API v1

You will be automatically redirected to the OAuth2 credentials configuration dialog. Choose "Desktop" when asked "Where are you calling from?"

In resulting dialog click DOWNLOAD CLIENT CONFIGURATION and save the file credentials.json to your working directory.

Alternatively, you can follow these steps to create an OAuth2 Credentials in an existing project manually.

Step 2. Install and initialize the Cloud SDK

You need the gcloud command line tool installed on your development machine.

Step 3: Make an API call

Now you can use the Google Analytics Data API to query a Google Analytics 4 property.

Select a Reporting Entity

In this tutorial, we will use the environment variable GA4_PROPERTY_ID to store the property ID to be used in API requests.

Enter the following on your command line to set the GA4_PROPERTY_ID variable:

export GA4_PROPERTY_ID=[YOUR-GA4-PROPERTY-ID]

Replace [YOUR-GA4-PROPERTY-ID] with your Google Analytics 4 property identifier. For example:

export GA4_PROPERTY_ID=1234567890

Create the Request JSON

The following request.json file demonstrates how to build a simple report.

Create the JSON request file with the following text, and save it as a request.json plain text file in your working directory:

request.json

{
  "dateRanges": [{ "startDate": "2020-09-01", "endDate": "2020-09-15" }],
  "dimensions": [{ "name": "country" }],
  "metrics": [{ "name": "activeUsers" }]
}

Authenticate

To obtain user credentials in this example, run the following command and use the path to the credentials JSON file downloaded at Step 1:

gcloud auth application-default login \
    --scopes=https://www.googleapis.com/auth/analytics.readonly \
    --client-id-file=[PATH/TO/credentials.json]

An OAuth user consent dialog will open in a new browser window.

Send the request

Use curl and the body content from request.json to send the request to the Google Analytics Data API. Enter the following on your command line:

  curl -X POST \
  -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
  -H "Content-Type: application/json; charset=utf-8" \
  https://analyticsdata.googleapis.com/v1beta/properties/$GA4_PROPERTY_ID:runReport -d @request.json

The curl command uses the gcloud auth application-default print-access-token command to get an authentication token.

Note that to pass a filename to curl you use the -d option (for "data") and precede the filename with an @ sign. This file should be in the same directory in which you execute the curl command.

Congratulations! You've sent your first request to the Google Analytics Data API.