Skip to content
This repository has been archived by the owner on Oct 31, 2023. It is now read-only.

Commit

Permalink
docs: add sample code for Data API v1 (#57)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
ikuleshov committed Apr 6, 2021
1 parent a55011d commit a1e63c5
Show file tree
Hide file tree
Showing 49 changed files with 2,270 additions and 13 deletions.
33 changes: 33 additions & 0 deletions samples/snippets/README.md
@@ -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
```
81 changes: 81 additions & 0 deletions samples/snippets/get_common_metadata.py
@@ -0,0 +1,81 @@
#!/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.
See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/getMetadata
for more information.
"""
# [START analyticsdata_get_common_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."""
get_common_metadata()


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

# 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)

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]


# [END analyticsdata_get_common_metadata]


if __name__ == "__main__":
run_sample()
21 changes: 21 additions & 0 deletions samples/snippets/get_common_metadata_test.py
@@ -0,0 +1,21 @@
# 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.

import get_common_metadata


def test_get_common_metadata(capsys):
get_common_metadata.get_common_metadata()
out, _ = capsys.readouterr()
assert "Dimensions and metrics" in out
56 changes: 56 additions & 0 deletions samples/snippets/get_metadata_by_property_id.py
@@ -0,0 +1,56 @@
#!/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.
See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/getMetadata
for more information.
"""
# [START analyticsdata_get_metadata_by_property_id]
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import GetMetadataRequest

from get_common_metadata import print_get_metadata_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"
get_metadata_by_property_id(property_id)


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()

request = GetMetadataRequest(name=f"properties/{property_id}/metadata")
response = client.get_metadata(request)

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


# [END analyticsdata_get_metadata_by_property_id]

if __name__ == "__main__":
run_sample()
25 changes: 25 additions & 0 deletions samples/snippets/get_metadata_by_property_id_test.py
@@ -0,0 +1,25 @@
# 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.

import os

import get_metadata_by_property_id

TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID")


def test_get_metadata_by_property_id(capsys):
get_metadata_by_property_id.get_metadata_by_property_id(TEST_PROPERTY_ID)
out, _ = capsys.readouterr()
assert "Dimensions and metrics" in out
5 changes: 1 addition & 4 deletions samples/snippets/quickstart.py
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 All @@ -48,7 +45,7 @@ def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):

# [START analyticsdata_run_report]
request = RunReportRequest(
property="properties/" + str(property_id),
property=f"properties/{property_id}",
dimensions=[Dimension(name="city")],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],
Expand Down
2 changes: 1 addition & 1 deletion samples/snippets/quickstart_json_credentials.py
Expand Up @@ -54,7 +54,7 @@ def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID", credentials_json_path=

# [START analyticsdata_json_credentials_run_report]
request = RunReportRequest(
property="properties/" + str(property_id),
property=f"properties/{property_id}",
dimensions=[Dimension(name="city")],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],
Expand Down
14 changes: 6 additions & 8 deletions samples/snippets/quickstart_oauth2.py
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 All @@ -44,7 +41,7 @@ def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"):

client = BetaAnalyticsDataClient(credentials=credentials)
request = RunReportRequest(
property="properties/" + str(property_id),
property=f"properties/{property_id}",
dimensions=[Dimension(name="city")],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],
Expand All @@ -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()
78 changes: 78 additions & 0 deletions samples/snippets/run_batch_report.py
@@ -0,0 +1,78 @@
#!/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.
See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/batchRunReports
for more information.
"""
# [START analyticsdata_run_batch_report]
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()

request = BatchRunReportsRequest(
property=f"properties/{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)

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


# [END analyticsdata_run_batch_report]


if __name__ == "__main__":
run_sample()

0 comments on commit a1e63c5

Please sign in to comment.