This repository has been archived by the owner on Nov 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: add sample code for Data API v1 (#57)
* docs: added a sample * docs: usage instructions updated to use Python3 * docs: updated sample to include main() method * docs: update the sample to support the Google Analytics Data API v1 beta * docs: add samples for the Data API v1 beta * update region tag names to match the convention * docs: add Data API v1 samples * add tests for new samples * add more samples * fix the test * fix tests * fix tests * fix tests * lint * lint * add README.md * fix time range in a query * temporary disable the threashold quota display * display pootentially thresholded requests per hour quota * lint * lint * removed noxfile.py from PR * removed generated configs from PR * removed generated configs from PR * remove generated configs from PR * Use f-strings instead of fortmat(). Use run_sample() to start the sample.. * move each sample into an individual file * move each sample into an individual file * fix region tags * fix tests
- Loading branch information
Showing
49 changed files
with
2,270 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
# Google Analytics Data API examples | ||
|
||
[![Open in Cloud Shell][shell_img]][shell_link] | ||
|
||
[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png | ||
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-analytics-data&page=editor&working_dir=samples/snippets | ||
|
||
These samples show how to use the | ||
[Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) from Python. | ||
|
||
## Build and Run | ||
1. **Enable APIs** - [Enable the Analytics Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com) | ||
and create a new project or select an existing project. | ||
2. **Download The Credentials** - Configure your project using [Application Default Credentials][adc]. | ||
Click "Go to credentials" after enabling the APIs. Click "Create Credentials" | ||
and select "Service Account Credentials" and download the credentials file. Then set the path to | ||
this file to the environment variable `GOOGLE_APPLICATION_CREDENTIALS`: | ||
```sh | ||
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json | ||
``` | ||
3. **Clone the repo** and cd into this directory | ||
```sh | ||
$ git clone https://github.com/googleapis/python-analytics-data | ||
$ cd python-analytics-data/samples/snippets | ||
``` | ||
4. **Install dependencies** via [pip3](https://pip.pypa.io/en/stable). | ||
Run `pip3 install --upgrade google-analytics-data`. | ||
5. **Review the comments starting with `TODO(developer)` and update the code | ||
to use correct values. | ||
6. **Run** with the command `python3 SNIPPET_NAME.py`. For example: | ||
```sh | ||
$ python3 quickstart.py | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
Oops, something went wrong.