Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
This repository was archived by the owner on Nov 9, 2024. It is now read-only.

Commit a1e63c5

Browse filesBrowse files
authored
docs: add sample code for Data API v1 (#57)
* docs: added a sample * docs: usage instructions updated to use Python3 * docs: updated sample to include main() method * docs: update the sample to support the Google Analytics Data API v1 beta * docs: add samples for the Data API v1 beta * update region tag names to match the convention * docs: add Data API v1 samples * add tests for new samples * add more samples * fix the test * fix tests * fix tests * fix tests * lint * lint * add README.md * fix time range in a query * temporary disable the threashold quota display * display pootentially thresholded requests per hour quota * lint * lint * removed noxfile.py from PR * removed generated configs from PR * removed generated configs from PR * remove generated configs from PR * Use f-strings instead of fortmat(). Use run_sample() to start the sample.. * move each sample into an individual file * move each sample into an individual file * fix region tags * fix tests
1 parent a55011d commit a1e63c5
Copy full SHA for a1e63c5

File tree

Expand file treeCollapse file tree

49 files changed

+2270
-13
lines changed
Filter options

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Dismiss banner
Expand file treeCollapse file tree

49 files changed

+2270
-13
lines changed

‎samples/snippets/README.md

Copy file name to clipboard
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Google Analytics Data API examples
2+
3+
[![Open in Cloud Shell][shell_img]][shell_link]
4+
5+
[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png
6+
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-analytics-data&page=editor&working_dir=samples/snippets
7+
8+
These samples show how to use the
9+
[Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) from Python.
10+
11+
## Build and Run
12+
1. **Enable APIs** - [Enable the Analytics Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com)
13+
and create a new project or select an existing project.
14+
2. **Download The Credentials** - Configure your project using [Application Default Credentials][adc].
15+
Click "Go to credentials" after enabling the APIs. Click "Create Credentials"
16+
and select "Service Account Credentials" and download the credentials file. Then set the path to
17+
this file to the environment variable `GOOGLE_APPLICATION_CREDENTIALS`:
18+
```sh
19+
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
20+
```
21+
3. **Clone the repo** and cd into this directory
22+
```sh
23+
$ git clone https://github.com/googleapis/python-analytics-data
24+
$ cd python-analytics-data/samples/snippets
25+
```
26+
4. **Install dependencies** via [pip3](https://pip.pypa.io/en/stable).
27+
Run `pip3 install --upgrade google-analytics-data`.
28+
5. **Review the comments starting with `TODO(developer)` and update the code
29+
to use correct values.
30+
6. **Run** with the command `python3 SNIPPET_NAME.py`. For example:
31+
```sh
32+
$ python3 quickstart.py
33+
```
+81Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2021 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Google Analytics Data API sample application retrieving dimension and metrics
18+
metadata.
19+
20+
See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/getMetadata
21+
for more information.
22+
"""
23+
# [START analyticsdata_get_common_metadata]
24+
from google.analytics.data_v1beta import BetaAnalyticsDataClient
25+
from google.analytics.data_v1beta.types import GetMetadataRequest
26+
from google.analytics.data_v1beta.types import MetricType
27+
28+
29+
def run_sample():
30+
"""Runs the sample."""
31+
get_common_metadata()
32+
33+
34+
def get_common_metadata():
35+
"""Retrieves dimensions and metrics available for all Google Analytics 4
36+
properties."""
37+
client = BetaAnalyticsDataClient()
38+
39+
# Set the Property ID to 0 for dimensions and metrics common
40+
# to all properties. In this special mode, this method will
41+
# not return custom dimensions and metrics.
42+
property_id = 0
43+
request = GetMetadataRequest(name=f"properties/{property_id}/metadata")
44+
response = client.get_metadata(request)
45+
46+
print("Dimensions and metrics available for all Google Analytics 4 properties:")
47+
print_get_metadata_response(response)
48+
49+
50+
def print_get_metadata_response(response):
51+
"""Prints results of the getMetadata call."""
52+
# [START analyticsdata_print_get_metadata_response]
53+
for dimension in response.dimensions:
54+
print("DIMENSION")
55+
print(f"{dimension.api_name} ({dimension.ui_name}): {dimension.description}")
56+
print(f"custom_definition: {dimension.custom_definition}")
57+
if dimension.deprecated_api_names:
58+
print(f"Deprecated API names: {dimension.deprecated_api_names}")
59+
print("")
60+
61+
for metric in response.metrics:
62+
print("METRIC")
63+
print(f"{metric.api_name} ({metric.ui_name}): {metric.description}")
64+
print(f"custom_definition: {dimension.custom_definition}")
65+
if metric.expression:
66+
print(f"Expression: {metric.expression}")
67+
68+
metric_type = MetricType(metric.type_).name
69+
print(f"Type: {metric_type}")
70+
71+
if metric.deprecated_api_names:
72+
print(f"Deprecated API names: {metric.deprecated_api_names}")
73+
print("")
74+
# [END analyticsdata_print_get_metadata_response]
75+
76+
77+
# [END analyticsdata_get_common_metadata]
78+
79+
80+
if __name__ == "__main__":
81+
run_sample()
+21Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Copyright 2021 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import get_common_metadata
16+
17+
18+
def test_get_common_metadata(capsys):
19+
get_common_metadata.get_common_metadata()
20+
out, _ = capsys.readouterr()
21+
assert "Dimensions and metrics" in out
+56Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2021 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Google Analytics Data API sample application retrieving dimension and metrics
18+
metadata.
19+
20+
See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/getMetadata
21+
for more information.
22+
"""
23+
# [START analyticsdata_get_metadata_by_property_id]
24+
from google.analytics.data_v1beta import BetaAnalyticsDataClient
25+
from google.analytics.data_v1beta.types import GetMetadataRequest
26+
27+
from get_common_metadata import print_get_metadata_response
28+
29+
30+
def run_sample():
31+
"""Runs the sample."""
32+
# TODO(developer): Replace this variable with your Google Analytics 4
33+
# property ID before running the sample.
34+
property_id = "YOUR-GA4-PROPERTY-ID"
35+
get_metadata_by_property_id(property_id)
36+
37+
38+
def get_metadata_by_property_id(property_id="YOUR-GA4-PROPERTY-ID"):
39+
"""Retrieves dimensions and metrics available for a Google Analytics 4
40+
property, including custom fields."""
41+
client = BetaAnalyticsDataClient()
42+
43+
request = GetMetadataRequest(name=f"properties/{property_id}/metadata")
44+
response = client.get_metadata(request)
45+
46+
print(
47+
f"Dimensions and metrics available for Google Analytics 4 "
48+
f"property {property_id} (including custom fields):"
49+
)
50+
print_get_metadata_response(response)
51+
52+
53+
# [END analyticsdata_get_metadata_by_property_id]
54+
55+
if __name__ == "__main__":
56+
run_sample()
+25Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Copyright 2021 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
17+
import get_metadata_by_property_id
18+
19+
TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID")
20+
21+
22+
def test_get_metadata_by_property_id(capsys):
23+
get_metadata_by_property_id.get_metadata_by_property_id(TEST_PROPERTY_ID)
24+
out, _ = capsys.readouterr()
25+
assert "Dimensions and metrics" in out

‎samples/snippets/quickstart.py

Copy file name to clipboardExpand all lines: samples/snippets/quickstart.py
+1-4Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,10 @@
1515
# limitations under the License.
1616

1717
"""Google Analytics Data API sample quickstart application.
18-
1918
This application demonstrates the usage of the Analytics Data API using
2019
service account credentials.
21-
2220
Before you start the application, please review the comments starting with
2321
"TODO(developer)" and update the code to use correct values.
24-
2522
Usage:
2623
pip3 install --upgrade google-analytics-data
2724
python3 quickstart.py
@@ -48,7 +45,7 @@ def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):
4845

4946
# [START analyticsdata_run_report]
5047
request = RunReportRequest(
51-
property="properties/" + str(property_id),
48+
property=f"properties/{property_id}",
5249
dimensions=[Dimension(name="city")],
5350
metrics=[Metric(name="activeUsers")],
5451
date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],

‎samples/snippets/quickstart_json_credentials.py

Copy file name to clipboardExpand all lines: samples/snippets/quickstart_json_credentials.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID", credentials_json_path=
5454

5555
# [START analyticsdata_json_credentials_run_report]
5656
request = RunReportRequest(
57-
property="properties/" + str(property_id),
57+
property=f"properties/{property_id}",
5858
dimensions=[Dimension(name="city")],
5959
metrics=[Metric(name="activeUsers")],
6060
date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],

‎samples/snippets/quickstart_oauth2.py

Copy file name to clipboardExpand all lines: samples/snippets/quickstart_oauth2.py
+6-8Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,16 @@
1515
# limitations under the License.
1616

1717
"""Google Analytics Data API sample quickstart application.
18-
1918
This application demonstrates the usage of the Analytics Data API using
2019
OAuth2 credentials.
21-
2220
Before you start the application, please review the comments starting with
2321
"TODO(developer)" and update the code to use correct values.
24-
2522
Usage:
2623
pip3 install --upgrade google-auth-oauthlib
2724
pip3 install --upgrade google-analytics-data
2825
python3 quickstart_oauth2.py
2926
"""
30-
# [START analyticsdata_quickstart_oauth2]
27+
# [START analyticsdata_oauth2_quickstart]
3128
from google.analytics.data import BetaAnalyticsDataClient
3229
from google.analytics.data_v1beta.types import DateRange
3330
from google.analytics.data_v1beta.types import Dimension
@@ -44,7 +41,7 @@ def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"):
4441

4542
client = BetaAnalyticsDataClient(credentials=credentials)
4643
request = RunReportRequest(
47-
property="properties/" + str(property_id),
44+
property=f"properties/{property_id}",
4845
dimensions=[Dimension(name="city")],
4946
metrics=[Metric(name="activeUsers")],
5047
date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],
@@ -59,7 +56,7 @@ def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"):
5956

6057
def get_credentials():
6158
"""Creates an OAuth2 credentials instance."""
62-
# [START analyticsdata_initialize]
59+
# [START analyticsdata_oauth2_initialize]
6360
appflow = flow.InstalledAppFlow.from_client_secrets_file(
6461
"client_secrets.json",
6562
scopes=["https://www.googleapis.com/auth/analytics.readonly"],
@@ -75,15 +72,16 @@ def get_credentials():
7572
else:
7673
appflow.run_console()
7774
return appflow.credentials
78-
# [END analyticsdata_initialize]
75+
# [END analyticsdata_oauth2_initialize]
7976

8077

8178
def main():
8279
credentials = get_credentials()
8380
sample_run_report(credentials)
8481

8582

86-
# [END analyticsdata_quickstart_oauth2]
83+
# [END analyticsdata_oauth2_quickstart]
84+
8785

8886
if __name__ == "__main__":
8987
main()

‎samples/snippets/run_batch_report.py

Copy file name to clipboard
+78Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2021 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Google Analytics Data API sample application demonstrating the batch creation
18+
of multiple reports.
19+
20+
See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/batchRunReports
21+
for more information.
22+
"""
23+
# [START analyticsdata_run_batch_report]
24+
from google.analytics.data_v1beta import BetaAnalyticsDataClient
25+
from google.analytics.data_v1beta.types import BatchRunReportsRequest
26+
from google.analytics.data_v1beta.types import DateRange
27+
from google.analytics.data_v1beta.types import Dimension
28+
from google.analytics.data_v1beta.types import Metric
29+
from google.analytics.data_v1beta.types import RunReportRequest
30+
31+
from run_report import print_run_report_response
32+
33+
34+
def run_sample():
35+
"""Runs the sample."""
36+
# TODO(developer): Replace this variable with your Google Analytics 4
37+
# property ID before running the sample.
38+
property_id = "YOUR-GA4-PROPERTY-ID"
39+
run_batch_report(property_id)
40+
41+
42+
def run_batch_report(property_id="YOUR-GA4-PROPERTY-ID"):
43+
"""Runs a batch report on a Google Analytics 4 property."""
44+
client = BetaAnalyticsDataClient()
45+
46+
request = BatchRunReportsRequest(
47+
property=f"properties/{property_id}",
48+
requests=[
49+
RunReportRequest(
50+
dimensions=[
51+
Dimension(name="country"),
52+
Dimension(name="region"),
53+
Dimension(name="city"),
54+
],
55+
metrics=[Metric(name="activeUsers")],
56+
date_ranges=[DateRange(start_date="2021-01-03", end_date="2021-01-09")],
57+
),
58+
RunReportRequest(
59+
dimensions=[
60+
Dimension(name="browser"),
61+
],
62+
metrics=[Metric(name="activeUsers")],
63+
date_ranges=[DateRange(start_date="2021-01-01", end_date="2021-01-31")],
64+
),
65+
],
66+
)
67+
response = client.batch_run_reports(request)
68+
69+
print("Batch report results:")
70+
for report in response.reports:
71+
print_run_report_response(report)
72+
73+
74+
# [END analyticsdata_run_batch_report]
75+
76+
77+
if __name__ == "__main__":
78+
run_sample()

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.