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/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