diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 0000000..da616c9 --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,3 @@ +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml new file mode 100644 index 0000000..4414ad9 --- /dev/null +++ b/.github/.OwlBot.yaml @@ -0,0 +1,26 @@ +# Copyright 2021 Google LLC +# +# 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. + +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + +deep-remove-regex: + - /owl-bot-staging + +deep-copy-regex: + - source: /google/analytics/data/(v.*)/.*-py/(.*) + dest: /owl-bot-staging/$1/$2 + +begin-after-commit-hash: a21f1091413a260393548c1b2ac44b7347923f08 + diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index fc281c0..6fe78aa 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], "sourceFileExtensions": [ "ts", "js", diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 5e94b60..3c81019 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google_cloud_pypi_password") +TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") cd github/python-analytics-data python3 setup.py sdist bdist_wheel -twine upload --username gcloudpypi --password "${TWINE_PASSWORD}" dist/* +twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index f0df3a7..c5b901a 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,18 +23,8 @@ env_vars: { value: "github/python-analytics-data/.kokoro/release.sh" } -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - # Tokens needed to report release status back to GitHub env_vars: { key: "SECRET_MANAGER_KEYS" - value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" -} \ No newline at end of file + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" +} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a9024b1..4f00c7c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,17 @@ +# Copyright 2021 Google LLC +# +# 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. +# # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: @@ -12,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.4 + rev: 3.9.2 hooks: - id: flake8 diff --git a/.repo-metadata.json b/.repo-metadata.json index 019ad78..bbf8320 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -6,6 +6,7 @@ "issue_tracker": "https://issuetracker.google.com/issues?q=componentid:187400%2B%20", "release_level": "beta", "language": "python", + "library_type": "GAPIC_AUTO", "repo": "googleapis/python-analytics-data", "distribution_name": "google-analytics-data", "api_id": "analyticsdata.googleapis.com", diff --git a/CHANGELOG.md b/CHANGELOG.md index e15e9a5..d1ee825 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +### [0.5.1](https://www.github.com/googleapis/python-analytics-data/compare/v0.5.0...v0.5.1) (2021-05-28) + + +### Bug Fixes + +* **deps:** require google-api-core>=1.22.2 ([675ae9f](https://www.github.com/googleapis/python-analytics-data/commit/675ae9fb45bc4ea1adbbba1a302f04daf6368fbf)) + + +### Documentation + +* add sample code for Data API v1 ([#57](https://www.github.com/googleapis/python-analytics-data/issues/57)) ([a1e63c5](https://www.github.com/googleapis/python-analytics-data/commit/a1e63c56f5fa5835c528724c9d861c18cb34d6ad)) + ## [0.5.0](https://www.github.com/googleapis/python-analytics-data/compare/v0.4.1...v0.5.0) (2021-04-01) diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 6f3e68d..559f9db 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests auth settings and change some configuration in your project to run all the tests. -- System tests will be run against an actual project and - so you'll need to provide some environment variables to facilitate - authentication to your project: - - - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file; - Such a file can be downloaded directly from the developer's console by clicking - "Generate new JSON key". See private key - `docs `__ - for more details. - -- Once you have downloaded your json keys, set the environment variable - ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file:: - - $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json" - +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. ************* Test Coverage diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..8b58ae9 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). + +The Google Security Team will respond within 5 working days of your report on g.co/vulnz. + +We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue. diff --git a/docs/_static/custom.css b/docs/_static/custom.css index bcd37bb..b0a2954 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,9 +1,20 @@ div#python2-eol { border-color: red; border-width: medium; -} +} /* Ensure minimum width for 'Parameters' / 'Returns' column */ dl.field-list > dt { min-width: 100px } + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/docs/conf.py b/docs/conf.py index f261e5b..40cb0ab 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +# Copyright 2021 Google LLC +# +# 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 documentation build configuration file # @@ -350,6 +363,7 @@ "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.github.io/grpc/python/", None), "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), } diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst index 1cb29d4..536d17b 100644 --- a/docs/multiprocessing.rst +++ b/docs/multiprocessing.rst @@ -1,7 +1,7 @@ .. note:: - Because this client uses :mod:`grpcio` library, it is safe to + Because this client uses :mod:`grpc` library, it is safe to share instances across threads. In multiprocessing scenarios, the best practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.Pool` or + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or :class:`multiprocessing.Process`. diff --git a/noxfile.py b/noxfile.py index 1f30a08..85c07fd 100644 --- a/noxfile.py +++ b/noxfile.py @@ -18,6 +18,7 @@ from __future__ import absolute_import import os +import pathlib import shutil import nox @@ -30,6 +31,8 @@ SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + # 'docfx' is excluded since it only needs to run in 'docs-presubmit' nox.options.sessions = [ "unit", @@ -59,16 +62,9 @@ def lint(session): session.run("flake8", "google", "tests") -@nox.session(python="3.6") +@nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): - """Run black. - - Format code to uniform standard. - - This currently uses Python 3.6 due to the automated Kokoro run of synthtool. - That run uses an image that doesn't have 3.6 installed. Before updating this - check the state of the `gcp_ubuntu_config` we use for that Kokoro run. - """ + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) session.run( "black", *BLACK_PATHS, @@ -84,13 +80,15 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. - session.install("asyncmock", "pytest-asyncio") - session.install( - "mock", "pytest", "pytest-cov", + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) + session.install("asyncmock", "pytest-asyncio", "-c", constraints_path) - session.install("-e", ".") + session.install("mock", "pytest", "pytest-cov", "-c", constraints_path) + + session.install("-e", ".", "-c", constraints_path) # Run py.test against the unit tests. session.run( @@ -117,15 +115,15 @@ def unit(session): @nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Sanity check: Only run tests if the environment variable is set. - if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): - session.skip("Credentials must be set via environment variable") # Install pyopenssl for mTLS testing. if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": session.install("pyopenssl") @@ -141,10 +139,8 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install( - "mock", "pytest", "google-cloud-testutils", - ) - session.install("-e", ".") + session.install("mock", "pytest", "google-cloud-testutils", "-c", constraints_path) + session.install("-e", ".", "-c", constraints_path) # Run py.test against the system tests. if system_test_exists: @@ -183,7 +179,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -205,9 +201,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - # sphinx-docfx-yaml supports up to sphinx version 1.5.5. - # https://github.com/docascode/sphinx-docfx-yaml/issues/97 - session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + session.install( + "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml" + ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/synth.py b/owlbot.py similarity index 73% rename from synth.py rename to owlbot.py index 27ce6d0..4e47074 100644 --- a/synth.py +++ b/owlbot.py @@ -19,31 +19,23 @@ import synthtool.gcp as gcp from synthtool.languages import python -gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() -versions = ["v1alpha", "v1beta"] - -# ---------------------------------------------------------------------------- -# Generate analytics data GAPIC layer -# ---------------------------------------------------------------------------- -for version in versions: - library = gapic.py_library( - service="analyticsdata", - version=version, - bazel_target=f"//google/analytics/data/{version}:google-analytics-data-{version}-py", - ) +default_version = "v1beta" +for library in s.get_staging_dirs(default_version): s.move( library, excludes=[ "setup.py", "README.rst", "docs/index.rst", - f"scripts/fixup_data_{version}_keywords.py", + f"scripts/fixup_data_{library.name}_keywords.py", ], ) +s.remove_staging_dirs() + # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- @@ -66,4 +58,4 @@ """``^[a-zA-Z0-9_]$``""", ) -s.shell.run(["nox", "-s", "blacken"], hide_output=False) +s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file diff --git a/renovate.json b/renovate.json index f08bc22..c048955 100644 --- a/renovate.json +++ b/renovate.json @@ -2,5 +2,8 @@ "extends": [ "config:base", ":preserveSemverRanges" ], - "ignorePaths": [".pre-commit-config.yaml"] + "ignorePaths": [".pre-commit-config.yaml"], + "pip_requirements": { + "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] + } } diff --git a/samples/snippets/README.md b/samples/snippets/README.md new file mode 100644 index 0000000..f390224 --- /dev/null +++ b/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 +``` diff --git a/samples/snippets/get_common_metadata.py b/samples/snippets/get_common_metadata.py new file mode 100644 index 0000000..731da0d --- /dev/null +++ b/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() diff --git a/samples/snippets/get_common_metadata_test.py b/samples/snippets/get_common_metadata_test.py new file mode 100644 index 0000000..ae11969 --- /dev/null +++ b/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 diff --git a/samples/snippets/get_metadata_by_property_id.py b/samples/snippets/get_metadata_by_property_id.py new file mode 100644 index 0000000..6950ced --- /dev/null +++ b/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() diff --git a/samples/snippets/get_metadata_by_property_id_test.py b/samples/snippets/get_metadata_by_property_id_test.py new file mode 100644 index 0000000..958f4b1 --- /dev/null +++ b/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 diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 7572097..ea1d771 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -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 @@ -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")], diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py index a30c8ea..97c2889 100644 --- a/samples/snippets/quickstart_json_credentials.py +++ b/samples/snippets/quickstart_json_credentials.py @@ -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")], diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 83aae0b..aa488ee 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -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 @@ -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")], @@ -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"], @@ -75,7 +72,7 @@ def get_credentials(): else: appflow.run_console() return appflow.credentials - # [END analyticsdata_initialize] + # [END analyticsdata_oauth2_initialize] def main(): @@ -83,7 +80,8 @@ def main(): sample_run_report(credentials) -# [END analyticsdata_quickstart_oauth2] +# [END analyticsdata_oauth2_quickstart] + if __name__ == "__main__": main() diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt index be53bec..95ea1e6 100644 --- a/samples/snippets/requirements-test.txt +++ b/samples/snippets/requirements-test.txt @@ -1 +1 @@ -pytest==6.1.1 +pytest==6.2.4 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 4d222ea..2b2d2d6 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,2 +1,2 @@ -google-analytics-data==0.4.0 +google-analytics-data==0.5.0 google-auth-oauthlib==0.4.4 \ No newline at end of file diff --git a/samples/snippets/run_batch_report.py b/samples/snippets/run_batch_report.py new file mode 100644 index 0000000..dfd155e --- /dev/null +++ b/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() diff --git a/samples/snippets/run_batch_report_test.py b/samples/snippets/run_batch_report_test.py new file mode 100644 index 0000000..880c10b --- /dev/null +++ b/samples/snippets/run_batch_report_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 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 diff --git a/samples/snippets/run_pivot_report.py b/samples/snippets/run_pivot_report.py new file mode 100644 index 0000000..dc3ce91 --- /dev/null +++ b/samples/snippets/run_pivot_report.py @@ -0,0 +1,99 @@ +#!/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 creation of +a pivot report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runPivotReport +for more information. +""" +# [START analyticsdata_run_pivot_report] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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 OrderBy +from google.analytics.data_v1beta.types import Pivot +from google.analytics.data_v1beta.types import RunPivotReportRequest + + +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_pivot_report(property_id) + + +def run_pivot_report(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a pivot query to build a report of session counts by country, + pivoted by the browser dimension..""" + client = BetaAnalyticsDataClient() + + request = RunPivotReportRequest( + property=f"properties/{property_id}", + date_ranges=[ + DateRange(start_date="2021-01-01", end_date="2021-01-30"), + ], + pivots=[ + Pivot( + field_names=["country"], + limit=250, + order_bys=[ + OrderBy( + dimension=OrderBy.DimensionOrderBy(dimension_name="country") + ) + ], + ), + Pivot( + field_names=["browser"], + offset=3, + limit=3, + order_bys=[ + OrderBy( + metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True + ) + ], + ), + ], + metrics=[Metric(name="sessions")], + dimensions=[ + Dimension(name="country"), + Dimension(name="browser"), + ], + ) + response = client.run_pivot_report(request) + print_run_pivot_report_response(response) + + +def print_run_pivot_report_response(response): + """Prints results of a runPivotReport call.""" + # [START analyticsdata_print_run_pivot_report_response] + print("Report result:") + for row in response.rows: + for dimension_value in row.dimension_values: + print(dimension_value.value) + + for metric_value in row.metric_values: + print(metric_value.value) + # [END analyticsdata_print_run_pivot_report_response] + + +# [END analyticsdata_run_pivot_report] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_pivot_report_test.py b/samples/snippets/run_pivot_report_test.py new file mode 100644 index 0000000..da010a1 --- /dev/null +++ b/samples/snippets/run_pivot_report_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 run_pivot_report + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_pivot_report(capsys): + run_pivot_report.run_pivot_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_realtime_report.py b/samples/snippets/run_realtime_report.py new file mode 100644 index 0000000..f106a16 --- /dev/null +++ b/samples/snippets/run_realtime_report.py @@ -0,0 +1,57 @@ +#!/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 creation of +a realtime report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport +for more information. +""" +# [START analyticsdata_run_realtime_report] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import RunRealtimeReportRequest + +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_realtime_report(property_id) + + +def run_realtime_report(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a realtime report on a Google Analytics 4 property.""" + client = BetaAnalyticsDataClient() + + request = RunRealtimeReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="country")], + metrics=[Metric(name="activeUsers")], + ) + response = client.run_realtime_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_realtime_report] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_realtime_report_test.py b/samples/snippets/run_realtime_report_test.py new file mode 100644 index 0000000..b0a643e --- /dev/null +++ b/samples/snippets/run_realtime_report_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 run_realtime_report + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_realtime_report(capsys): + run_realtime_report.run_realtime_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_realtime_report_with_multiple_dimensions.py b/samples/snippets/run_realtime_report_with_multiple_dimensions.py new file mode 100644 index 0000000..3726681 --- /dev/null +++ b/samples/snippets/run_realtime_report_with_multiple_dimensions.py @@ -0,0 +1,57 @@ +#!/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 creation of +a realtime report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport +for more information. +""" +# [START analyticsdata_run_realtime_report_with_multiple_dimensions] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import RunRealtimeReportRequest + +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_realtime_report_with_multiple_dimensions(property_id) + + +def run_realtime_report_with_multiple_dimensions(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a realtime report on a Google Analytics 4 property.""" + client = BetaAnalyticsDataClient() + + request = RunRealtimeReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="country"), Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + ) + response = client.run_realtime_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_realtime_report_with_multiple_dimensions] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_realtime_report_with_multiple_dimensions_test.py b/samples/snippets/run_realtime_report_with_multiple_dimensions_test.py new file mode 100644 index 0000000..2f0f057 --- /dev/null +++ b/samples/snippets/run_realtime_report_with_multiple_dimensions_test.py @@ -0,0 +1,27 @@ +# 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 run_report_with_multiple_dimensions + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_multiple_dimensions(capsys): + run_report_with_multiple_dimensions.run_report_with_multiple_dimensions( + TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_realtime_report_with_multiple_metrics.py b/samples/snippets/run_realtime_report_with_multiple_metrics.py new file mode 100644 index 0000000..c87731d --- /dev/null +++ b/samples/snippets/run_realtime_report_with_multiple_metrics.py @@ -0,0 +1,57 @@ +#!/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 creation of +a realtime report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport +for more information. +""" +# [START analyticsdata_run_realtime_report_with_multiple_metrics] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import RunRealtimeReportRequest + +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_realtime_report_with_multiple_metrics(property_id) + + +def run_realtime_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a realtime report on a Google Analytics 4 property.""" + client = BetaAnalyticsDataClient() + + request = RunRealtimeReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="unifiedScreenName")], + metrics=[Metric(name="screenPageViews"), Metric(name="conversions")], + ) + response = client.run_realtime_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_realtime_report_with_multiple_metrics] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_realtime_report_with_multiple_metrics_test.py b/samples/snippets/run_realtime_report_with_multiple_metrics_test.py new file mode 100644 index 0000000..92ab1eb --- /dev/null +++ b/samples/snippets/run_realtime_report_with_multiple_metrics_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 run_report_with_multiple_metrics + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_multiple_metrics(capsys): + run_report_with_multiple_metrics.run_report_with_multiple_metrics(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report.py b/samples/snippets/run_report.py new file mode 100644 index 0000000..c76f5ea --- /dev/null +++ b/samples/snippets/run_report.py @@ -0,0 +1,80 @@ +#!/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 creation +of a basic report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport +for more information. +""" +# [START analyticsdata_run_report] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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 MetricType +from google.analytics.data_v1beta.types import RunReportRequest + + +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_report(property_id) + + +def run_report(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report of active users grouped by country.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="country")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-09-01", end_date="2020-09-15")], + ) + response = client.run_report(request) + print_run_report_response(response) + + +def print_run_report_response(response): + """Prints results of a runReport call.""" + # [START analyticsdata_print_run_report_response_header] + print(f"{response.row_count} rows received") + for dimensionHeader in response.dimension_headers: + print(f"Dimension header name: {dimensionHeader.name}") + for metricHeader in response.metric_headers: + metric_type = MetricType(metricHeader.type_).name + print(f"Metric header name: {metricHeader.name} ({metric_type})") + # [END analyticsdata_print_run_report_response_header] + + # [START analyticsdata_print_run_report_response_rows] + print("Report result:") + for row in response.rows: + for dimension_value in row.dimension_values: + print(dimension_value.value) + + for metric_value in row.metric_values: + print(metric_value.value) + # [END analyticsdata_print_run_report_response_rows] + + +# [END analyticsdata_run_report] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_test.py b/samples/snippets/run_report_test.py new file mode 100644 index 0000000..d6e6f2f --- /dev/null +++ b/samples/snippets/run_report_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 run_report + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_basic(capsys): + run_report.run_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_aggregations.py b/samples/snippets/run_report_with_aggregations.py new file mode 100644 index 0000000..3b77fd8 --- /dev/null +++ b/samples/snippets/run_report_with_aggregations.py @@ -0,0 +1,66 @@ +#!/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 usage of +metric aggregations in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.metric_aggregations +for more information. +""" +# [START analyticsdata_run_report_with_aggregations] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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 MetricAggregation +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_report_with_aggregations(property_id) + + +def run_report_with_aggregations(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report which includes total, maximum and minimum values for + each metric.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="country")], + metrics=[Metric(name="sessions")], + date_ranges=[DateRange(start_date="365daysAgo", end_date="today")], + metric_aggregations=[ + MetricAggregation.TOTAL, + MetricAggregation.MAXIMUM, + MetricAggregation.MINIMUM, + ], + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_aggregations] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_aggregations_test.py b/samples/snippets/run_report_with_aggregations_test.py new file mode 100644 index 0000000..420c412 --- /dev/null +++ b/samples/snippets/run_report_with_aggregations_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 run_report_with_aggregations + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_aggregations(capsys): + run_report_with_aggregations.run_report_with_aggregations(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_cohorts.py b/samples/snippets/run_report_with_cohorts.py new file mode 100644 index 0000000..4bf15a5 --- /dev/null +++ b/samples/snippets/run_report_with_cohorts.py @@ -0,0 +1,85 @@ +#!/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 demonstratinf the usage of +cohort specification in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.cohort_spec +for more information. +""" +# [START analyticsdata_run_report_with_cohorts] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import Cohort +from google.analytics.data_v1beta.types import CohortSpec +from google.analytics.data_v1beta.types import CohortsRange +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_report_with_cohorts(property_id) + + +def run_report_with_cohorts(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report on a cohort of users whose first session happened on the + same week. The number of active users and user retention rate is calculated + for the cohort using WEEKLY granularity.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="cohort"), Dimension(name="cohortNthWeek")], + metrics=[ + Metric(name="cohortActiveUsers"), + Metric( + name="cohortRetentionRate", + expression="cohortActiveUsers/cohortTotalUsers", + ), + ], + cohort_spec=CohortSpec( + cohorts=[ + Cohort( + dimension="firstSessionDate", + name="cohort", + date_range=DateRange( + start_date="2021-01-03", end_date="2021-01-09" + ), + ) + ], + cohorts_range=CohortsRange( + start_offset=0, + end_offset=4, + granularity=CohortsRange.Granularity.WEEKLY, + ), + ), + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_cohorts] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_cohorts_test.py b/samples/snippets/run_report_with_cohorts_test.py new file mode 100644 index 0000000..06907e7 --- /dev/null +++ b/samples/snippets/run_report_with_cohorts_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 run_report_with_cohorts + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_cohorts(capsys): + run_report_with_cohorts.run_report_with_cohorts(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_custom_parameters.py b/samples/snippets/run_report_with_custom_parameters.py new file mode 100644 index 0000000..e0a3191 --- /dev/null +++ b/samples/snippets/run_report_with_custom_parameters.py @@ -0,0 +1,41 @@ +#!/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. +""" +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import RunReportRequest + + +def run_report_with_custom_parameters(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a simple report on a Google Analytics 4 property.""" + client = BetaAnalyticsDataClient() + + # [START run_report_with_custom_parameters] + request = RunReportRequest() + response = client.run_report(request) + # [END run_report_with_custom_parameters] + + print("Report result:") + for row in response.rows: + print(row.dimension_values[0].value, row.metric_values[0].value) + + +if __name__ == "__main__": + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + run_report_with_custom_parameters(property_id) diff --git a/samples/snippets/run_report_with_date_ranges.py b/samples/snippets/run_report_with_date_ranges.py new file mode 100644 index 0000000..73fae80 --- /dev/null +++ b/samples/snippets/run_report_with_date_ranges.py @@ -0,0 +1,62 @@ +#!/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 usage of +date ranges in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.date_ranges +for more information. +""" +# [START analyticsdata_run_report_with_date_ranges] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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_report_with_date_ranges(property_id) + + +def run_report_with_date_ranges(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report using two date ranges.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + date_ranges=[ + DateRange(start_date="2019-08-01", end_date="2019-08-14"), + DateRange(start_date="2020-08-01", end_date="2020-08-14"), + ], + dimensions=[Dimension(name="platform")], + metrics=[Metric(name="activeUsers")], + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_date_ranges] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_date_ranges_test.py b/samples/snippets/run_report_with_date_ranges_test.py new file mode 100644 index 0000000..552f969 --- /dev/null +++ b/samples/snippets/run_report_with_date_ranges_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 run_report_with_date_ranges + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_date_ranges(capsys): + run_report_with_date_ranges.run_report_with_date_ranges(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_dimension_and_metric_filters.py b/samples/snippets/run_report_with_dimension_and_metric_filters.py new file mode 100644 index 0000000..8935e32 --- /dev/null +++ b/samples/snippets/run_report_with_dimension_and_metric_filters.py @@ -0,0 +1,99 @@ +#!/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 usage of +dimension and metric filters in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter +for more information. +""" +# [START analyticsdata_run_report_with_dimension_and_metric_filters] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Filter +from google.analytics.data_v1beta.types import FilterExpression +from google.analytics.data_v1beta.types import FilterExpressionList +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import NumericValue +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_report_with_dimension_and_metric_filters(property_id) + + +def run_report_with_dimension_and_metric_filters(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report using both metric and dimension filters. A dimension filter + limits the report to include only users who made an in-app purchase using + Android platform. A metric filter specifies that only users with session + counts larger than 1,000 should be included.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], + metric_filter=FilterExpression( + filter=Filter( + field_name="sessions", + numeric_filter=Filter.NumericFilter( + operation=Filter.NumericFilter.Operation.GREATER_THAN, + value=NumericValue(int64_value=1000), + ), + ) + ), + dimension_filter=FilterExpression( + and_group=FilterExpressionList( + expressions=[ + FilterExpression( + filter=Filter( + field_name="platform", + string_filter=Filter.StringFilter( + match_type=Filter.StringFilter.MatchType.EXACT, + value="Android", + ), + ) + ), + FilterExpression( + filter=Filter( + field_name="eventName", + string_filter=Filter.StringFilter( + match_type=Filter.StringFilter.MatchType.EXACT, + value="in_app_purchase", + ), + ) + ), + ] + ) + ), + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_dimension_and_metric_filters] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_dimension_and_metric_filters_test.py b/samples/snippets/run_report_with_dimension_and_metric_filters_test.py new file mode 100644 index 0000000..5499574 --- /dev/null +++ b/samples/snippets/run_report_with_dimension_and_metric_filters_test.py @@ -0,0 +1,27 @@ +# 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 run_report_with_dimension_and_metric_filters + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_dimension_and_metric_filters(capsys): + run_report_with_dimension_and_metric_filters.run_report_with_dimension_and_metric_filters( + TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_dimension_exclude_filter.py b/samples/snippets/run_report_with_dimension_exclude_filter.py new file mode 100644 index 0000000..938cee9 --- /dev/null +++ b/samples/snippets/run_report_with_dimension_exclude_filter.py @@ -0,0 +1,74 @@ +#!/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 usage of +dimension and metric filters in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter +for more information. +""" +# [START analyticsdata_run_report_with_dimension_exclude_filter] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Filter +from google.analytics.data_v1beta.types import FilterExpression +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_report_with_dimension_exclude_filter(property_id) + + +def run_report_with_dimension_exclude_filter(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report using a filter with `not_expression`. The dimension filter + selects for when `pageTitle` is not `My Homepage`. + + This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange + for more information. + """ + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="pageTitle")], + metrics=[Metric(name="sessions")], + date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], + dimension_filter=FilterExpression( + not_expression=FilterExpression( + filter=Filter( + field_name="pageTitle", + string_filter=Filter.StringFilter(value="My Homepage"), + ) + ) + ), + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_dimension_exclude_filter] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_dimension_exclude_filter_test.py b/samples/snippets/run_report_with_dimension_exclude_filter_test.py new file mode 100644 index 0000000..3cef3fb --- /dev/null +++ b/samples/snippets/run_report_with_dimension_exclude_filter_test.py @@ -0,0 +1,27 @@ +# 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 run_report_with_dimension_exclude_filter + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_dimension_exclude_filter(capsys): + run_report_with_dimension_exclude_filter.run_report_with_dimension_exclude_filter( + TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_dimension_filter.py b/samples/snippets/run_report_with_dimension_filter.py new file mode 100644 index 0000000..d9568a7 --- /dev/null +++ b/samples/snippets/run_report_with_dimension_filter.py @@ -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 usage of +dimension and metric filters in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter +for more information. +""" +# [START analyticsdata_run_report_with_dimension_filter] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Filter +from google.analytics.data_v1beta.types import FilterExpression +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_report_with_dimension_filter(property_id) + + +def run_report_with_dimension_filter(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report using a dimension filter. The call returns a time series + report of `eventCount` when `eventName` is `first_open` for each date. + + This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange + for more information. + """ + + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="date")], + metrics=[Metric(name="eventCount")], + date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], + dimension_filter=FilterExpression( + filter=Filter( + field_name="eventName", + string_filter=Filter.StringFilter(value="first_open"), + ) + ), + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_dimension_filter] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_dimension_filter_test.py b/samples/snippets/run_report_with_dimension_filter_test.py new file mode 100644 index 0000000..b4e5791 --- /dev/null +++ b/samples/snippets/run_report_with_dimension_filter_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 run_report_with_dimension_filter + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_dimension_filter(capsys): + run_report_with_dimension_filter.run_report_with_dimension_filter(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_dimension_in_list_filter.py b/samples/snippets/run_report_with_dimension_in_list_filter.py new file mode 100644 index 0000000..e4bd7e3 --- /dev/null +++ b/samples/snippets/run_report_with_dimension_in_list_filter.py @@ -0,0 +1,79 @@ +#!/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 usage of +dimension and metric filters in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter +for more information. +""" +# [START analyticsdata_run_report_with_dimension_in_list_filter] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Filter +from google.analytics.data_v1beta.types import FilterExpression +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_report_with_dimension_in_list_filter(property_id) + + +def run_report_with_dimension_in_list_filter(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report using a dimension filter with `in_list_filter` expression. + The filter selects for when `eventName` is set to one of three event names + specified in the query. + + This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange + for more information. + """ + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="eventName")], + metrics=[Metric(name="sessions")], + date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], + dimension_filter=FilterExpression( + filter=Filter( + field_name="eventName", + in_list_filter=Filter.InListFilter( + values=[ + "purchase", + "in_app_purchase", + "app_store_subscription_renew", + ] + ), + ) + ), + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_dimension_in_list_filter] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_dimension_in_list_filter_test.py b/samples/snippets/run_report_with_dimension_in_list_filter_test.py new file mode 100644 index 0000000..60f34a5 --- /dev/null +++ b/samples/snippets/run_report_with_dimension_in_list_filter_test.py @@ -0,0 +1,27 @@ +# 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 run_report_with_dimension_in_list_filter + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_dimension_in_list_filter(capsys): + run_report_with_dimension_in_list_filter.run_report_with_dimension_in_list_filter( + TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_multiple_dimension_filters.py b/samples/snippets/run_report_with_multiple_dimension_filters.py new file mode 100644 index 0000000..e1002af --- /dev/null +++ b/samples/snippets/run_report_with_multiple_dimension_filters.py @@ -0,0 +1,86 @@ +#!/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 usage of +dimension and metric filters in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter +for more information. +""" +# [START analyticsdata_run_report_with_multiple_dimension_filters] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Filter +from google.analytics.data_v1beta.types import FilterExpression +from google.analytics.data_v1beta.types import FilterExpressionList +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_report_with_multiple_dimension_filters(property_id) + + +def run_report_with_multiple_dimension_filters(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report using multiple dimension filters joined as `and_group` + expression. The filter selects for when both `browser` is `Chrome` and + `countryId` is `US`. + + This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange + for more information. + """ + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="browser")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], + dimension_filter=FilterExpression( + and_group=FilterExpressionList( + expressions=[ + FilterExpression( + filter=Filter( + field_name="browser", + string_filter=Filter.StringFilter(value="Chrome"), + ) + ), + FilterExpression( + filter=Filter( + field_name="countryId", + string_filter=Filter.StringFilter(value="US"), + ) + ), + ] + ) + ), + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_multiple_dimension_filters] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_multiple_dimension_filters_test.py b/samples/snippets/run_report_with_multiple_dimension_filters_test.py new file mode 100644 index 0000000..82f2160 --- /dev/null +++ b/samples/snippets/run_report_with_multiple_dimension_filters_test.py @@ -0,0 +1,27 @@ +# 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 run_report_with_multiple_dimension_filters + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_multiple_dimension_filters(capsys): + run_report_with_multiple_dimension_filters.run_report_with_multiple_dimension_filters( + TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_multiple_dimensions.py b/samples/snippets/run_report_with_multiple_dimensions.py new file mode 100644 index 0000000..78a4a1c --- /dev/null +++ b/samples/snippets/run_report_with_multiple_dimensions.py @@ -0,0 +1,62 @@ +#!/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 creation +of a basic report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport +for more information. +""" +# [START analyticsdata_run_report_with_multiple_dimensions] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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_report_with_multiple_dimensions(property_id) + + +def run_report_with_multiple_dimensions(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report of active users grouped by three dimensions.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[ + Dimension(name="country"), + Dimension(name="region"), + Dimension(name="city"), + ], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="7daysAgo", end_date="today")], + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_multiple_dimensions] + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_multiple_dimensions_test.py b/samples/snippets/run_report_with_multiple_dimensions_test.py new file mode 100644 index 0000000..2f0f057 --- /dev/null +++ b/samples/snippets/run_report_with_multiple_dimensions_test.py @@ -0,0 +1,27 @@ +# 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 run_report_with_multiple_dimensions + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_multiple_dimensions(capsys): + run_report_with_multiple_dimensions.run_report_with_multiple_dimensions( + TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_multiple_metrics.py b/samples/snippets/run_report_with_multiple_metrics.py new file mode 100644 index 0000000..d3546df --- /dev/null +++ b/samples/snippets/run_report_with_multiple_metrics.py @@ -0,0 +1,64 @@ +#!/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 creation +of a basic report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport +for more information. +""" +# [START analyticsdata_run_report_with_multiple_metrics] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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_report_with_multiple_metrics(property_id) + + +def run_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report of active users, new users and total revenue grouped by + date dimension.""" + client = BetaAnalyticsDataClient() + + # Runs a report of active users grouped by three dimensions. + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="date")], + metrics=[ + Metric(name="activeUsers"), + Metric(name="newUsers"), + Metric(name="totalRevenue"), + ], + date_ranges=[DateRange(start_date="7daysAgo", end_date="today")], + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_multiple_metrics] + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_multiple_metrics_test.py b/samples/snippets/run_report_with_multiple_metrics_test.py new file mode 100644 index 0000000..92ab1eb --- /dev/null +++ b/samples/snippets/run_report_with_multiple_metrics_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 run_report_with_multiple_metrics + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_multiple_metrics(capsys): + run_report_with_multiple_metrics.run_report_with_multiple_metrics(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_named_date_ranges.py b/samples/snippets/run_report_with_named_date_ranges.py new file mode 100644 index 0000000..a4f0d17 --- /dev/null +++ b/samples/snippets/run_report_with_named_date_ranges.py @@ -0,0 +1,64 @@ +#!/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 usage of +date ranges in a report. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange#FIELDS.name +for more information. +""" +# [START analyticsdata_run_report_with_date_ranges] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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_report_with_named_date_ranges(property_id) + + +def run_report_with_named_date_ranges(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report using named date ranges.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + date_ranges=[ + DateRange(start_date="2020-01-01", end_date="2020-01-31", name="year_ago"), + DateRange( + start_date="2021-01-01", end_date="2021-01-31", name="current_year" + ), + ], + dimensions=[Dimension(name="country")], + metrics=[Metric(name="sessions")], + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_date_ranges] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_named_date_ranges_test.py b/samples/snippets/run_report_with_named_date_ranges_test.py new file mode 100644 index 0000000..0c0637f --- /dev/null +++ b/samples/snippets/run_report_with_named_date_ranges_test.py @@ -0,0 +1,27 @@ +# 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 run_report_with_named_date_ranges + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_named_date_ranges(capsys): + run_report_with_named_date_ranges.run_report_with_named_date_ranges( + TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_ordering.py b/samples/snippets/run_report_with_ordering.py new file mode 100644 index 0000000..f55bf5c --- /dev/null +++ b/samples/snippets/run_report_with_ordering.py @@ -0,0 +1,68 @@ +#!/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 ordering of + report rows. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.order_bys +for more information. +""" +# [START analyticsdata_run_report_with_ordering] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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 OrderBy +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_report_with_ordering(property_id) + + +def run_report_with_ordering(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report of active users grouped by three dimensions, ordered by + the total revenue in descending order.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + dimensions=[Dimension(name="date")], + metrics=[ + Metric(name="activeUsers"), + Metric(name="newUsers"), + Metric(name="totalRevenue"), + ], + date_ranges=[DateRange(start_date="7daysAgo", end_date="today")], + order_bys=[ + OrderBy(metric=OrderBy.MetricOrderBy(metric_name="totalRevenue"), desc=True) + ], + ) + response = client.run_report(request) + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_ordering] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_ordering_test.py b/samples/snippets/run_report_with_ordering_test.py new file mode 100644 index 0000000..28c7297 --- /dev/null +++ b/samples/snippets/run_report_with_ordering_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 run_report_with_ordering + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_ordering(capsys): + run_report_with_ordering.run_report_with_ordering(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_pagination.py b/samples/snippets/run_report_with_pagination.py new file mode 100644 index 0000000..487f325 --- /dev/null +++ b/samples/snippets/run_report_with_pagination.py @@ -0,0 +1,95 @@ +#!/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 use of +pagination to retrieve large result sets. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.offset +for more information. +""" +# [START analyticsdata_run_report_with_pagination] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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_report_with_pagination(property_id) + + +def run_report_with_pagination(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report several times, each time retrieving a portion of result + using pagination.""" + client = BetaAnalyticsDataClient() + + # [START analyticsdata_run_report_with_pagination_page1] + request = RunReportRequest( + property=f"properties/{property_id}", + date_ranges=[DateRange(start_date="365daysAgo", end_date="yesterday")], + dimensions=[ + Dimension(name="firstUserSource"), + Dimension(name="firstUserMedium"), + Dimension(name="firstUserCampaignName"), + ], + metrics=[ + Metric(name="sessions"), + Metric(name="conversions"), + Metric(name="totalRevenue"), + ], + limit=100000, + offset=0, + ) + response = client.run_report(request) + # [END analyticsdata_run_report_with_pagination_page1] + print_run_report_response(response) + + # Run the same report with a different offset value to retrieve the second + # page of a response. + # [START analyticsdata_run_report_with_pagination_page2] + request = RunReportRequest( + property=f"properties/{property_id}", + date_ranges=[DateRange(start_date="365daysAgo", end_date="yesterday")], + dimensions=[ + Dimension(name="firstUserSource"), + Dimension(name="firstUserMedium"), + Dimension(name="firstUserCampaignName"), + ], + metrics=[ + Metric(name="sessions"), + Metric(name="conversions"), + Metric(name="totalRevenue"), + ], + limit=100000, + offset=100000, + ) + response = client.run_report(request) + # [END analyticsdata_run_report_with_pagination_page2] + print_run_report_response(response) + + +# [END analyticsdata_run_report_with_pagination] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_pagination_test.py b/samples/snippets/run_report_with_pagination_test.py new file mode 100644 index 0000000..b9b65e7 --- /dev/null +++ b/samples/snippets/run_report_with_pagination_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 run_report_with_pagination + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_pagination(capsys): + run_report_with_pagination.run_report_with_pagination(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/run_report_with_property_quota.py b/samples/snippets/run_report_with_property_quota.py new file mode 100644 index 0000000..f62414a --- /dev/null +++ b/samples/snippets/run_report_with_property_quota.py @@ -0,0 +1,86 @@ +#!/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 usage of +property quota metadata. + +See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.return_property_quota +for more information. +""" +# [START analyticsdata_run_report_with_property_quota] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +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 + + +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_report_with_property_quota(property_id) + + +def run_report_with_property_quota(property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a report and prints property quota information.""" + client = BetaAnalyticsDataClient() + + request = RunReportRequest( + property=f"properties/{property_id}", + return_property_quota=True, + dimensions=[Dimension(name="country")], + metrics=[ + Metric(name="activeUsers"), + ], + date_ranges=[DateRange(start_date="7daysAgo", end_date="today")], + ) + response = client.run_report(request) + + # [START analyticsdata_run_report_with_property_quota_print_response] + if response.property_quota: + print( + f"Tokens per day quota consumed: {response.property_quota.tokens_per_day.consumed}, " + f"remaining: {response.property_quota.tokens_per_day.remaining}." + ) + + print( + f"Tokens per hour quota consumed: {response.property_quota.tokens_per_hour.consumed}, " + f"remaining: {response.property_quota.tokens_per_hour.remaining}." + ) + + print( + f"Concurrent requests quota consumed: {response.property_quota.concurrent_requests.consumed}, " + f"remaining: {response.property_quota.concurrent_requests.remaining}." + ) + + print( + f"Server errors per project per hour quota consumed: {response.property_quota.server_errors_per_project_per_hour.consumed}, " + f"remaining: {response.property_quota.server_errors_per_project_per_hour.remaining}." + ) + print( + f"Potentially thresholded requests per hour quota consumed: {response.property_quota.potentially_thresholded_requests_per_hour.consumed}, " + f"remaining: {response.property_quota.potentially_thresholded_requests_per_hour.remaining}." + ) + # [END analyticsdata_run_report_with_property_quota_print_response] + + +# [END analyticsdata_run_report_with_property_quota] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/snippets/run_report_with_property_quota_test.py b/samples/snippets/run_report_with_property_quota_test.py new file mode 100644 index 0000000..1b17fb8 --- /dev/null +++ b/samples/snippets/run_report_with_property_quota_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 run_report_with_property_quota + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_run_report_with_property_quota(capsys): + run_report_with_property_quota.run_report_with_property_quota(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Tokens per day quota consumed" in out diff --git a/setup.py b/setup.py index 6e8c419..3370d8d 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import setuptools # type: ignore -version = "0.5.0" +version = "0.5.1" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -41,7 +41,7 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "libcst >= 0.2.5", "proto-plus >= 1.4.0", ), diff --git a/synth.metadata b/synth.metadata deleted file mode 100644 index 1729cec..0000000 --- a/synth.metadata +++ /dev/null @@ -1,165 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "https://github.com/googleapis/python-analytics-data.git", - "sha": "1c1d58f1ee88e50ce92c40b0ec58c19cec631297" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "95dd24960cf9f794ef583e59ad9f1fabe1c4a924", - "internalRef": "365882072" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "79c8dd7ee768292f933012d3a69a5b4676404cda" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "79c8dd7ee768292f933012d3a69a5b4676404cda" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "analyticsdata", - "apiVersion": "v1alpha", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "analyticsdata", - "apiVersion": "v1beta", - "language": "python", - "generator": "bazel" - } - } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/header-checker-lint.yml", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic-head.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic-head.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic-head.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples-against-head.sh", - ".kokoro/test-samples-impl.sh", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".pre-commit-config.yaml", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/data_v1alpha/alpha_analytics_data.rst", - "docs/data_v1alpha/services.rst", - "docs/data_v1alpha/types.rst", - "docs/data_v1beta/beta_analytics_data.rst", - "docs/data_v1beta/services.rst", - "docs/data_v1beta/types.rst", - "docs/multiprocessing.rst", - "google/analytics/data/__init__.py", - "google/analytics/data/py.typed", - "google/analytics/data_v1alpha/__init__.py", - "google/analytics/data_v1alpha/py.typed", - "google/analytics/data_v1alpha/services/__init__.py", - "google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py", - "google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py", - "google/analytics/data_v1alpha/services/alpha_analytics_data/client.py", - "google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py", - "google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py", - "google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py", - "google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py", - "google/analytics/data_v1alpha/types/__init__.py", - "google/analytics/data_v1alpha/types/analytics_data_api.py", - "google/analytics/data_v1alpha/types/data.py", - "google/analytics/data_v1beta/__init__.py", - "google/analytics/data_v1beta/py.typed", - "google/analytics/data_v1beta/services/__init__.py", - "google/analytics/data_v1beta/services/beta_analytics_data/__init__.py", - "google/analytics/data_v1beta/services/beta_analytics_data/async_client.py", - "google/analytics/data_v1beta/services/beta_analytics_data/client.py", - "google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py", - "google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py", - "google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py", - "google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py", - "google/analytics/data_v1beta/types/__init__.py", - "google/analytics/data_v1beta/types/analytics_data_api.py", - "google/analytics/data_v1beta/types/data.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "scripts/decrypt-secrets.sh", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/data_v1alpha/__init__.py", - "tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py", - "tests/unit/gapic/data_v1beta/__init__.py", - "tests/unit/gapic/data_v1beta/test_beta_analytics_data.py" - ] -} \ No newline at end of file diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index e4e5e44..16e003f 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -5,6 +5,6 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.22.0 +google-api-core==1.22.2 libcst==0.2.5 -proto-plus==1.4.0 \ No newline at end of file +proto-plus==1.4.0