Skip to content
This repository has been archived by the owner on Nov 9, 2024. It is now read-only.

docs: add sample code for Data API v1 #57

Merged
merged 42 commits into from
Apr 6, 2021
Merged
Show file tree
Hide file tree
Changes from 37 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
fc5a4d6
docs: added a sample
ikuleshov Sep 24, 2020
bfd3488
Merge branch 'master' into samples
ikuleshov Oct 7, 2020
0a74ac1
docs: usage instructions updated to use Python3
ikuleshov Nov 5, 2020
7f709d3
Merge branch 'samples' of github.com:ikuleshov/python-analytics-data …
ikuleshov Nov 5, 2020
4156c32
docs: updated sample to include main() method
ikuleshov Jan 5, 2021
a4be69d
Merge branch 'master' into samples
ikuleshov Jan 5, 2021
b59f40d
docs: update the sample to support the Google Analytics Data API v1 beta
ikuleshov Feb 26, 2021
d5a1e4f
docs: add samples for the Data API v1 beta
ikuleshov Mar 16, 2021
5758766
Merge branch 'master' into beta_samples
ikuleshov Mar 23, 2021
0128e9a
update region tag names to match the convention
ikuleshov Mar 25, 2021
1000d00
Merge remote-tracking branch 'upstream/master' into beta_samples
ikuleshov Mar 25, 2021
1caa0d8
docs: add Data API v1 samples
ikuleshov Mar 25, 2021
04b9410
add tests for new samples
ikuleshov Mar 25, 2021
5d2bd1a
add more samples
ikuleshov Mar 31, 2021
0f219db
Merge remote-tracking branch 'upstream/master' into beta_samples
ikuleshov Mar 31, 2021
4e45676
fix the test
ikuleshov Mar 31, 2021
ec8c3e3
fix tests
ikuleshov Mar 31, 2021
9261ed9
fix tests
ikuleshov Mar 31, 2021
02d48ee
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov Mar 31, 2021
3101379
fix tests
ikuleshov Mar 31, 2021
3a4f71c
lint
ikuleshov Mar 31, 2021
1b27792
lint
ikuleshov Mar 31, 2021
4bf15ed
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov Apr 1, 2021
5a6eb2b
add README.md
ikuleshov Apr 1, 2021
95f3389
fix time range in a query
ikuleshov Apr 2, 2021
08ca5d4
temporary disable the threashold quota display
ikuleshov Apr 2, 2021
463e260
Merge remote-tracking branch 'upstream/master' into beta_samples
ikuleshov Apr 2, 2021
c05c8d5
display pootentially thresholded requests per hour quota
ikuleshov Apr 2, 2021
22a0fa0
lint
ikuleshov Apr 2, 2021
278cdf4
lint
ikuleshov Apr 2, 2021
065527e
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov Apr 2, 2021
480b994
removed noxfile.py from PR
ikuleshov Apr 2, 2021
ed35edc
removed generated configs from PR
ikuleshov Apr 2, 2021
3e172e8
removed generated configs from PR
ikuleshov Apr 2, 2021
5f3f217
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov Apr 2, 2021
f1a36bb
remove generated configs from PR
ikuleshov Apr 2, 2021
b0637cb
Use f-strings instead of fortmat(). Use run_sample() to start the sam…
ikuleshov Apr 5, 2021
72e2b12
move each sample into an individual file
ikuleshov Apr 6, 2021
a987b88
move each sample into an individual file
ikuleshov Apr 6, 2021
e561f02
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov Apr 6, 2021
f6dae8f
fix region tags
ikuleshov Apr 6, 2021
f511e7c
fix tests
ikuleshov Apr 6, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions samples/snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Google Analytics Data API examples

[![Open in Cloud Shell][shell_img]][shell_link]

[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-analytics-data&page=editor&working_dir=samples/snippets

These samples show how to use the
[Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) from Python.

## Build and Run
1. **Enable APIs** - [Enable the Analytics Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com)
and create a new project or select an existing project.
2. **Download The Credentials** - Configure your project using [Application Default Credentials][adc].
Click "Go to credentials" after enabling the APIs. Click "Create Credentials"
and select "Service Account Credentials" and download the credentials file. Then set the path to
this file to the environment variable `GOOGLE_APPLICATION_CREDENTIALS`:
```sh
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
```
3. **Clone the repo** and cd into this directory
```sh
$ git clone https://github.com/googleapis/python-analytics-data
$ cd python-analytics-data/samples/snippets
```
4. **Install dependencies** via [pip3](https://pip.pypa.io/en/stable).
Run `pip3 install --upgrade google-analytics-data`.
5. **Review the comments starting with `TODO(developer)` and update the code
to use correct values.
6. **Run** with the command `python3 SNIPPET_NAME.py`. For example:
```sh
$ python3 quickstart.py
```
97 changes: 97 additions & 0 deletions samples/snippets/get_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/usr/bin/env python

# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Google Analytics Data API sample application retrieving dimension and metrics
metadata.
"""
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import GetMetadataRequest
from google.analytics.data_v1beta.types import MetricType


def run_sample():
"""Runs the sample."""
# TODO(developer): Replace this variable with your Google Analytics 4
# property ID before running the sample.
property_id = "YOUR-GA4-PROPERTY-ID"
get_metadata_by_property_id(property_id)
get_common_metadata()


def get_metadata_by_property_id(property_id="YOUR-GA4-PROPERTY-ID"):
"""Retrieves dimensions and metrics available for a Google Analytics 4
property, including custom fields."""
client = BetaAnalyticsDataClient()

# [START analyticsdata_get_metadata_by_property_id]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regions tags should show enough the user can copy/paste them to run, including imports - see "Region Tags" in the authoring guide.

It's also generally preferred to have 1 snippet per file.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(same everywhere)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kurtis, we do follow this advice for quickstart samples. However, other snippets are included in the API usage guides that demonstrate the usage of various API features inside one document (e.g. "Advanced API Features Guide", "Migration Guide"). It is therefore useful to include just the relevant part of the snippet to illustrate the feature. If a user wants to see the complete example, they can follow a link to GitHub.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is an example of the guide we will need to include the samples into:
https://developers.devsite.corp.google.com/analytics/devguides/reporting/data/v1/basics

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I grouped certain samples together in one file since they demonstrate the same concept (e.g. run_report_with_filters.py), just with different queries. Creating a separate file for each sample looks a bit redundant here, though we may consider separating these in the future. The more use cases we demonstrate, the easier it will be for the users to adopt the API...

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we should do it for each sample. The goal is that samples should be "copy-paste-runnable" - most users want to be able to copy a sample, paste it into their own environment, and run it immediately with only minor changes. This is what the sample format is optimizing for.

It may seem redundant but having each sample isolated into its own file makes it easier to ensure only used imports are included and that each snippet make sense without additional context.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree this makes sense. I moved each sample into a separate file and moved region tags around to include the entire sample.

request = GetMetadataRequest(name=f"properties/{property_id}/metadata")
response = client.get_metadata(request)
# [END analyticsdata_get_metadata_by_property_id]

print(
f"Dimensions and metrics available for Google Analytics 4 "
f"property {property_id} (including custom fields):"
)
print_get_metadata_response(response)


def get_common_metadata():
"""Retrieves dimensions and metrics available for all Google Analytics 4
properties."""
client = BetaAnalyticsDataClient()

# [START analyticsdata_get_common_metadata]
# Set the Property ID to 0 for dimensions and metrics common
# to all properties. In this special mode, this method will
# not return custom dimensions and metrics.
property_id = 0
request = GetMetadataRequest(name=f"properties/{property_id}/metadata")
response = client.get_metadata(request)
# [END analyticsdata_get_common_metadata]

print("Dimensions and metrics available for all Google Analytics 4 properties:")
print_get_metadata_response(response)


def print_get_metadata_response(response):
"""Prints results of the getMetadata call."""
# [START analyticsdata_print_get_metadata_response]
for dimension in response.dimensions:
print("DIMENSION")
print(f"{dimension.api_name} ({dimension.ui_name}): {dimension.description}")
print(f"custom_definition: {dimension.custom_definition}")
if dimension.deprecated_api_names:
print(f"Deprecated API names: {dimension.deprecated_api_names}")
print("")

for metric in response.metrics:
print("METRIC")
print(f"{metric.api_name} ({metric.ui_name}): {metric.description}")
print(f"custom_definition: {dimension.custom_definition}")
if metric.expression:
print(f"Expression: {metric.expression}")

metric_type = MetricType(metric.type_).name
print(f"Type: {metric_type}")

if metric.deprecated_api_names:
print(f"Deprecated API names: {metric.deprecated_api_names}")
print("")
# [END analyticsdata_print_get_metadata_response]


if __name__ == "__main__":
run_sample()
31 changes: 31 additions & 0 deletions samples/snippets/get_metadata_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright 2020 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import get_metadata

TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID")


def test_get_common_metadata(capsys):
get_metadata.get_common_metadata()
out, _ = capsys.readouterr()
assert "Dimensions and metrics" in out


def test_get_metadata_by_property_id(capsys):
get_metadata.get_metadata_by_property_id(TEST_PROPERTY_ID)
out, _ = capsys.readouterr()
assert "Dimensions and metrics" in out
3 changes: 0 additions & 3 deletions samples/snippets/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@
# limitations under the License.

"""Google Analytics Data API sample quickstart application.

This application demonstrates the usage of the Analytics Data API using
service account credentials.

Before you start the application, please review the comments starting with
"TODO(developer)" and update the code to use correct values.

Usage:
pip3 install --upgrade google-analytics-data
python3 quickstart.py
Expand Down
12 changes: 5 additions & 7 deletions samples/snippets/quickstart_oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,16 @@
# limitations under the License.

"""Google Analytics Data API sample quickstart application.

This application demonstrates the usage of the Analytics Data API using
OAuth2 credentials.

Before you start the application, please review the comments starting with
"TODO(developer)" and update the code to use correct values.

Usage:
pip3 install --upgrade google-auth-oauthlib
pip3 install --upgrade google-analytics-data
python3 quickstart_oauth2.py
"""
# [START analyticsdata_quickstart_oauth2]
# [START analyticsdata_oauth2_quickstart]
from google.analytics.data import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange
from google.analytics.data_v1beta.types import Dimension
Expand Down Expand Up @@ -59,7 +56,7 @@ def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"):

def get_credentials():
"""Creates an OAuth2 credentials instance."""
# [START analyticsdata_initialize]
# [START analyticsdata_oauth2_initialize]
appflow = flow.InstalledAppFlow.from_client_secrets_file(
"client_secrets.json",
scopes=["https://www.googleapis.com/auth/analytics.readonly"],
Expand All @@ -75,15 +72,16 @@ def get_credentials():
else:
appflow.run_console()
return appflow.credentials
# [END analyticsdata_initialize]
# [END analyticsdata_oauth2_initialize]


def main():
credentials = get_credentials()
sample_run_report(credentials)


# [END analyticsdata_quickstart_oauth2]
# [END analyticsdata_oauth2_quickstart]


if __name__ == "__main__":
main()
73 changes: 73 additions & 0 deletions samples/snippets/run_batch_report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/env python

# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Google Analytics Data API sample application demonstrating the batch creation
of multiple reports.
"""
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import BatchRunReportsRequest
from google.analytics.data_v1beta.types import DateRange
from google.analytics.data_v1beta.types import Dimension
from google.analytics.data_v1beta.types import Metric
from google.analytics.data_v1beta.types import RunReportRequest

from run_report import print_run_report_response


def run_sample():
"""Runs the sample."""
# TODO(developer): Replace this variable with your Google Analytics 4
# property ID before running the sample.
property_id = "YOUR-GA4-PROPERTY-ID"
run_batch_report(property_id)


def run_batch_report(property_id="YOUR-GA4-PROPERTY-ID"):
"""Runs a batch report on a Google Analytics 4 property."""
client = BetaAnalyticsDataClient()

# [START analyticsdata_run_batch_report]
request = BatchRunReportsRequest(
property="properties/" + str(property_id),
requests=[
RunReportRequest(
dimensions=[
Dimension(name="country"),
Dimension(name="region"),
Dimension(name="city"),
],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2021-01-03", end_date="2021-01-09")],
),
RunReportRequest(
dimensions=[
Dimension(name="browser"),
],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2021-01-01", end_date="2021-01-31")],
),
],
)
response = client.batch_run_reports(request)
# [END analyticsdata_run_batch_report]

print("Batch report results:")
for report in response.reports:
print_run_report_response(report)


if __name__ == "__main__":
run_sample()
25 changes: 25 additions & 0 deletions samples/snippets/run_batch_report_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright 2020 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import run_batch_report

TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID")


def test_run_batch_report(capsys):
run_batch_report.run_batch_report(TEST_PROPERTY_ID)
out, _ = capsys.readouterr()
assert "Batch report result" in out
Loading