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
docs: add sample code for Data API v1 #57
Merged
Merged
Changes from 37 commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
fc5a4d6
docs: added a sample
ikuleshov bfd3488
Merge branch 'master' into samples
ikuleshov 0a74ac1
docs: usage instructions updated to use Python3
ikuleshov 7f709d3
Merge branch 'samples' of github.com:ikuleshov/python-analytics-data …
ikuleshov 4156c32
docs: updated sample to include main() method
ikuleshov a4be69d
Merge branch 'master' into samples
ikuleshov b59f40d
docs: update the sample to support the Google Analytics Data API v1 beta
ikuleshov d5a1e4f
docs: add samples for the Data API v1 beta
ikuleshov 5758766
Merge branch 'master' into beta_samples
ikuleshov 0128e9a
update region tag names to match the convention
ikuleshov 1000d00
Merge remote-tracking branch 'upstream/master' into beta_samples
ikuleshov 1caa0d8
docs: add Data API v1 samples
ikuleshov 04b9410
add tests for new samples
ikuleshov 5d2bd1a
add more samples
ikuleshov 0f219db
Merge remote-tracking branch 'upstream/master' into beta_samples
ikuleshov 4e45676
fix the test
ikuleshov ec8c3e3
fix tests
ikuleshov 9261ed9
fix tests
ikuleshov 02d48ee
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov 3101379
fix tests
ikuleshov 3a4f71c
lint
ikuleshov 1b27792
lint
ikuleshov 4bf15ed
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov 5a6eb2b
add README.md
ikuleshov 95f3389
fix time range in a query
ikuleshov 08ca5d4
temporary disable the threashold quota display
ikuleshov 463e260
Merge remote-tracking branch 'upstream/master' into beta_samples
ikuleshov c05c8d5
display pootentially thresholded requests per hour quota
ikuleshov 22a0fa0
lint
ikuleshov 278cdf4
lint
ikuleshov 065527e
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov 480b994
removed noxfile.py from PR
ikuleshov ed35edc
removed generated configs from PR
ikuleshov 3e172e8
removed generated configs from PR
ikuleshov 5f3f217
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov f1a36bb
remove generated configs from PR
ikuleshov b0637cb
Use f-strings instead of fortmat(). Use run_sample() to start the sam…
ikuleshov 72e2b12
move each sample into an individual file
ikuleshov a987b88
move each sample into an individual file
ikuleshov e561f02
Merge branch 'beta_samples' of github.com:ikuleshov/python-analytics-…
ikuleshov f6dae8f
fix region tags
ikuleshov f511e7c
fix tests
ikuleshov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,97 @@ | ||
#!/usr/bin/env python | ||
|
||
# Copyright 2021 Google Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Google Analytics Data API sample application retrieving dimension and metrics | ||
metadata. | ||
""" | ||
from google.analytics.data_v1beta import BetaAnalyticsDataClient | ||
from google.analytics.data_v1beta.types import GetMetadataRequest | ||
from google.analytics.data_v1beta.types import MetricType | ||
|
||
|
||
def run_sample(): | ||
"""Runs the sample.""" | ||
# TODO(developer): Replace this variable with your Google Analytics 4 | ||
# property ID before running the sample. | ||
property_id = "YOUR-GA4-PROPERTY-ID" | ||
get_metadata_by_property_id(property_id) | ||
get_common_metadata() | ||
|
||
|
||
def get_metadata_by_property_id(property_id="YOUR-GA4-PROPERTY-ID"): | ||
"""Retrieves dimensions and metrics available for a Google Analytics 4 | ||
property, including custom fields.""" | ||
client = BetaAnalyticsDataClient() | ||
|
||
# [START analyticsdata_get_metadata_by_property_id] | ||
request = GetMetadataRequest(name=f"properties/{property_id}/metadata") | ||
response = client.get_metadata(request) | ||
# [END analyticsdata_get_metadata_by_property_id] | ||
|
||
print( | ||
f"Dimensions and metrics available for Google Analytics 4 " | ||
f"property {property_id} (including custom fields):" | ||
) | ||
print_get_metadata_response(response) | ||
|
||
|
||
def get_common_metadata(): | ||
"""Retrieves dimensions and metrics available for all Google Analytics 4 | ||
properties.""" | ||
client = BetaAnalyticsDataClient() | ||
|
||
# [START analyticsdata_get_common_metadata] | ||
# Set the Property ID to 0 for dimensions and metrics common | ||
# to all properties. In this special mode, this method will | ||
# not return custom dimensions and metrics. | ||
property_id = 0 | ||
request = GetMetadataRequest(name=f"properties/{property_id}/metadata") | ||
response = client.get_metadata(request) | ||
# [END analyticsdata_get_common_metadata] | ||
|
||
print("Dimensions and metrics available for all Google Analytics 4 properties:") | ||
print_get_metadata_response(response) | ||
|
||
|
||
def print_get_metadata_response(response): | ||
"""Prints results of the getMetadata call.""" | ||
# [START analyticsdata_print_get_metadata_response] | ||
for dimension in response.dimensions: | ||
print("DIMENSION") | ||
print(f"{dimension.api_name} ({dimension.ui_name}): {dimension.description}") | ||
print(f"custom_definition: {dimension.custom_definition}") | ||
if dimension.deprecated_api_names: | ||
print(f"Deprecated API names: {dimension.deprecated_api_names}") | ||
print("") | ||
|
||
for metric in response.metrics: | ||
print("METRIC") | ||
print(f"{metric.api_name} ({metric.ui_name}): {metric.description}") | ||
print(f"custom_definition: {dimension.custom_definition}") | ||
if metric.expression: | ||
print(f"Expression: {metric.expression}") | ||
|
||
metric_type = MetricType(metric.type_).name | ||
print(f"Type: {metric_type}") | ||
|
||
if metric.deprecated_api_names: | ||
print(f"Deprecated API names: {metric.deprecated_api_names}") | ||
print("") | ||
# [END analyticsdata_print_get_metadata_response] | ||
|
||
|
||
if __name__ == "__main__": | ||
run_sample() |
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,31 @@ | ||
# Copyright 2020 Google Inc. All Rights Reserved. | ||
ikuleshov marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import os | ||
|
||
import get_metadata | ||
|
||
TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") | ||
|
||
|
||
def test_get_common_metadata(capsys): | ||
get_metadata.get_common_metadata() | ||
out, _ = capsys.readouterr() | ||
assert "Dimensions and metrics" in out | ||
|
||
|
||
def test_get_metadata_by_property_id(capsys): | ||
get_metadata.get_metadata_by_property_id(TEST_PROPERTY_ID) | ||
out, _ = capsys.readouterr() | ||
assert "Dimensions and metrics" in out |
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,73 @@ | ||
#!/usr/bin/env python | ||
|
||
# Copyright 2021 Google Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Google Analytics Data API sample application demonstrating the batch creation | ||
of multiple reports. | ||
""" | ||
from google.analytics.data_v1beta import BetaAnalyticsDataClient | ||
from google.analytics.data_v1beta.types import BatchRunReportsRequest | ||
from google.analytics.data_v1beta.types import DateRange | ||
from google.analytics.data_v1beta.types import Dimension | ||
from google.analytics.data_v1beta.types import Metric | ||
from google.analytics.data_v1beta.types import RunReportRequest | ||
|
||
from run_report import print_run_report_response | ||
|
||
|
||
def run_sample(): | ||
"""Runs the sample.""" | ||
# TODO(developer): Replace this variable with your Google Analytics 4 | ||
# property ID before running the sample. | ||
property_id = "YOUR-GA4-PROPERTY-ID" | ||
run_batch_report(property_id) | ||
|
||
|
||
def run_batch_report(property_id="YOUR-GA4-PROPERTY-ID"): | ||
"""Runs a batch report on a Google Analytics 4 property.""" | ||
client = BetaAnalyticsDataClient() | ||
|
||
# [START analyticsdata_run_batch_report] | ||
request = BatchRunReportsRequest( | ||
property="properties/" + str(property_id), | ||
requests=[ | ||
RunReportRequest( | ||
dimensions=[ | ||
Dimension(name="country"), | ||
Dimension(name="region"), | ||
Dimension(name="city"), | ||
], | ||
metrics=[Metric(name="activeUsers")], | ||
date_ranges=[DateRange(start_date="2021-01-03", end_date="2021-01-09")], | ||
), | ||
RunReportRequest( | ||
dimensions=[ | ||
Dimension(name="browser"), | ||
], | ||
metrics=[Metric(name="activeUsers")], | ||
date_ranges=[DateRange(start_date="2021-01-01", end_date="2021-01-31")], | ||
), | ||
], | ||
) | ||
response = client.batch_run_reports(request) | ||
# [END analyticsdata_run_batch_report] | ||
|
||
print("Batch report results:") | ||
for report in response.reports: | ||
print_run_report_response(report) | ||
|
||
|
||
if __name__ == "__main__": | ||
run_sample() |
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 2020 Google Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import os | ||
|
||
import run_batch_report | ||
|
||
TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") | ||
|
||
|
||
def test_run_batch_report(capsys): | ||
run_batch_report.run_batch_report(TEST_PROPERTY_ID) | ||
out, _ = capsys.readouterr() | ||
assert "Batch report result" in out |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Regions tags should show enough the user can copy/paste them to run, including imports - see "Region Tags" in the authoring guide.
It's also generally preferred to have 1 snippet per file.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(same everywhere)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Kurtis, we do follow this advice for quickstart samples. However, other snippets are included in the API usage guides that demonstrate the usage of various API features inside one document (e.g. "Advanced API Features Guide", "Migration Guide"). It is therefore useful to include just the relevant part of the snippet to illustrate the feature. If a user wants to see the complete example, they can follow a link to GitHub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here is an example of the guide we will need to include the samples into:
https://developers.devsite.corp.google.com/analytics/devguides/reporting/data/v1/basics
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also, I grouped certain samples together in one file since they demonstrate the same concept (e.g.
run_report_with_filters.py
), just with different queries. Creating a separate file for each sample looks a bit redundant here, though we may consider separating these in the future. The more use cases we demonstrate, the easier it will be for the users to adopt the API...There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, we should do it for each sample. The goal is that samples should be "copy-paste-runnable" - most users want to be able to copy a sample, paste it into their own environment, and run it immediately with only minor changes. This is what the sample format is optimizing for.
It may seem redundant but having each sample isolated into its own file makes it easier to ensure only used imports are included and that each snippet make sense without additional context.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree this makes sense. I moved each sample into a separate file and moved region tags around to include the entire sample.