1
---
2
name: google-analytics-data-api-basics
3
metadata:
4
version: "1.0.0"
5
category: GoogleAnalytics
6
description: >-
7
Manages Google Analytics reporting data, enables the Analytics Data API via the Cloud CLI, and creates reports using the Google Analytics Data API (v1beta). Use when you need to interact with Google Analytics properties, run customized analytics reports, query metrics (like activeUsers, screenPageViews) and dimensions (like city, date), check metrics and dimensions compatibility, or verify API enablement. Don't use for Google Analytics Admin API operations (e.g., creating properties, managing users) or for front-end tracking installation.
8
---
9
10
# Getting Started with Google Analytics Data API
11
12
The Google Analytics Data API v1beta provides programmatic access to Google
13
Analytics report data. It allows you to build customized dashboards,
14
automate reporting workflows, and integrate Google Analytics data into your enterprise
15
applications.
16
17
## Enabling the API via Cloud CLI
18
19
Before making API calls, ensure the Google Analytics Data API is enabled in your
20
Google Cloud project.
21
22
If `gcloud` is not found, prompt the user to install the Google Cloud CLI before
23
running these commands.
24
25
1. **Enable the API:** Use the Cloud CLI (`gcloud`) to enable
26
`analyticsdata.googleapis.com`.
27
28
```bash
29
gcloud services enable analyticsdata.googleapis.com --quiet
30
```
31
32
*Why: Enabling the API ensures your Cloud project has the necessary quota
33
and permissions allocated for running Google Analytics reports.*
34
35
2. **Verify API Enablement:**
36
37
```bash
38
gcloud services list --enabled --filter="analyticsdata.googleapis.com"
39
```
40
41
## Authentication
42
43
To authenticate your API requests, you must generate Application Default
44
Credentials (ADC) and give your account the necessary scopes. Run the following
45
command in your terminal:
46
47
```bash
48
gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
49
```
50
51
*Why: This configures ADC in your local environment with the required Cloud
52
Platform and Google Analytics read-only scopes, allowing the client library to
53
automatically authenticate your requests.*
54
55
## Creating a Data API Report (v1beta)
56
57
To create a report, use the official Google Analytics Data client library.
58
Always prefer the `v1beta` version of the API for stability and access to
59
current Google Analytics reporting capabilities.
60
61
> [!IMPORTANT] **Mandatory Agent Directive:** When the user selects or requires
62
> a specific programming language, read the corresponding client library setup
63
> reference guide in `references/` listed below.
64
65
### Supported Client Libraries
66
67
#### Python
68
69
If you need to install or set up the Google Analytics Data API client library
70
for Python, read the setup guide:
71
72
* [Python Installation Reference](references/python.md) *(Package:
73
`google-analytics-data`)*
74
75
#### Java
76
77
If you need to install or set up the Google Analytics Data API client library
78
for Java, read the setup guide:
79
80
* [Java Installation Reference](references/java.md) *(Artifact:
81
`com.google.cloud:google-cloud-analytics-data`)*
82
83
#### PHP
84
85
If you need to install or set up the Google Analytics Data API client library
86
for PHP, read the setup guide:
87
88
* [PHP Installation Reference](references/php.md) *(Package:
89
`google/analytics-data`)*
90
91
#### Node.js
92
93
If you need to install or set up the Google Analytics Data API client library
94
for Node.js, read the setup guide:
95
96
* [Node.js Installation Reference](references/nodejs.md) *(Package:
97
`@google-analytics/data`)*
98
99
#### Go
100
101
If you need to install or set up the Google Analytics Data API client library
102
for Go, read the setup guide:
103
104
* [Go Installation Reference](references/go.md) *(Package:
105
`cloud.google.com/go/analytics/data/apiv1beta`)*
106
107
#### .NET
108
109
If you need to install or set up the Google Analytics Data API client library
110
for .NET / C#, read the setup guide:
111
112
* [.NET Installation Reference](references/dotnet.md) *(Package:
113
`Google.Analytics.Data.V1Beta`)*
114
115
#### Ruby
116
117
If you need to install or set up the Google Analytics Data API client library
118
for Ruby, read the setup guide:
119
120
* [Ruby Installation Reference](references/ruby.md) *(Gem:
121
`google-analytics-data-v1beta`)*
122
123
> [!NOTE] **Additional Resources**: For further examples of calling the Data API
124
> with Java, PHP, Node.js, .NET, Python and REST, as well as hints on
125
> authentication with a service account, refer to the official
126
> [Data API Quickstart](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart).
127
128
### Python Quick Start
129
130
1. **Install the Client Library:**
131
132
```bash
133
pip install google-analytics-data
134
```
135
136
If `pip` is not available, prompt the user to install `pip` before
137
installing the client library.
138
139
2. **Run a Report Request:** Below is a complete example demonstrating how to
140
query a Google Analytics property for active users and sessions grouped by city and date.
141
Replace `YOUR-PROPERTY-ID` with your actual Google Analytics property ID (e.g.,
142
`1234567`).
143
144
```python
145
from google.analytics.data_v1beta import BetaAnalyticsDataClient
146
from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest
147
148
def sample_run_report(property_id: str):
149
# Initialize the client.
150
# Assumes Application Default Credentials (ADC) are configured in your environment.
151
client = BetaAnalyticsDataClient()
152
153
request = RunReportRequest(
154
property=f"properties/{property_id}",
155
dimensions=[
156
Dimension(name="city"),
157
Dimension(name="date")
158
],
159
metrics=[
160
Metric(name="activeUsers"),
161
Metric(name="sessions")
162
],
163
date_ranges=[
164
DateRange(start_date="2026-05-01", end_date="today")
165
],
166
)
167
168
response = client.run_report(request)
169
170
print(f"Report result for property {property_id}:")
171
for row in response.rows:
172
print(
173
f"City: {row.dimension_values[0].value}, "
174
f"Date: {row.dimension_values[1].value}, "
175
f"Active Users: {row.metric_values[0].value}, "
176
f"Sessions: {row.metric_values[1].value}"
177
)
178
179
if __name__ == "__main__":
180
sample_run_report("YOUR-PROPERTY-ID")
181
```
182
183
*Why: Using `BetaAnalyticsDataClient` and `RunReportRequest` ensures
184
compatibility with the v1beta endpoint and strongly typed request
185
validation.*
186
187
## Metrics and Dimensions Schema
188
189
When constructing your `RunReportRequest`, you must use valid API names for
190
dimensions and metrics. Refer to the official
191
[Data API Schema documentation](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema)
192
for the complete, authoritative list of available fields.
193
194
### Commonly Used Dimensions
195
196
Dimensions represent categorical attributes of your data.
197
198
* `city`: The town or city of the user.
199
* `country`: The country of the user.
200
* `date`: The date of the event, formatted as YYYYMMDD.
201
* `deviceCategory`: The category of mobile device (e.g., desktop, mobile,
202
tablet).
203
* `eventName`: The name of the triggered event.
204
* `pageTitle`: The title of the web page.
205
206
### Commonly Used Metrics
207
208
Metrics represent quantitative measurements.
209
210
* `activeUsers`: The number of active users.
211
* `eventCount`: The total count of events.
212
* `sessions`: The total number of sessions.
213
* `screenPageViews`: The number of app screens or web pages viewed.
214
* `totalRevenue`: The total revenue from purchases, subscriptions, and
215
advertising.
216
217
### Metrics and Dimensions Compatibility Check
218
219
Some dimensions and metrics cannot be queried together in the same report
220
request. If you encounter an `INVALID_ARGUMENT` error regarding incompatible
221
fields, verify your field combinations For programmatic access to the Data API
222
schema, use `getMetadata()`. To programmatically check the compatibility of
223
specific dimension and metric combinations before running a report, use the
224
`checkCompatibility()` method.
225
226
```python
227
from google.analytics.data_v1beta import BetaAnalyticsDataClient
228
from google.analytics.data_v1beta.types import CheckCompatibilityRequest, Compatibility, Dimension, Metric
229
230
def sample_check_compatibility(property_id: str):
231
client = BetaAnalyticsDataClient()
232
233
# Define the dimensions and metrics you want to query together.
234
# For example, checking if 'itemName' (an e-commerce dimension)
235
# is compatible with 'activeUsers' and 'totalRevenue'.
236
request = CheckCompatibilityRequest(
237
property=f"properties/{property_id}",
238
dimensions=[
239
Dimension(name="itemName"),
240
Dimension(name="date")
241
],
242
metrics=[
243
Metric(name="activeUsers"),
244
Metric(name="totalRevenue")
245
],
246
)
247
response = client.check_compatibility(request)
248
249
print(f"Compatibility check for property {property_id}:")
250
for dim in response.dimension_compatibilities:
251
is_compatible = dim.compatibility == Compatibility.COMPATIBLE
252
print(f"Dimension '{dim.dimension_metadata.api_name}' is compatible: {is_compatible}")
253
254
for metric in response.metric_compatibilities:
255
is_compatible = metric.compatibility == Compatibility.COMPATIBLE
256
print(f"Metric '{metric.metric_metadata.api_name}' is compatible: {is_compatible}")
257
258
if __name__ == "__main__":
259
sample_check_compatibility("YOUR-PROPERTY-ID")
260
```
261