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 the following button to create a new Google Cloud project, automatically enable the Google Analytics Data API v1 and create the OAuth2 credentials needed for this tutorial:
Enable the Google Analytics Data API v1You will be automatically redirected to the OAuth2 credentials configuration dialog. When the dialog asks Where are you calling from?, choose Desktop.
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 property.
Select a Reporting Entity
In this tutorial, we will use the environment variable GA_PROPERTY_ID
to store
the property ID to be used in API requests.
Enter the following on your command line to set the GA_PROPERTY_ID
variable:
export GA_PROPERTY_ID=[YOUR_GA_PROPERTY_ID]
Replace [YOUR_GA_PROPERTY_ID]
with your Google Analytics property
identifier. For example:
export GA_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/$GA_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.