這篇介紹Python連接Google Analytics 4 API取得資料。
啟用API
Google Cloud新增專案
在Google Cloud裡新增專案,點選專案列表,在Google Cloud左上角這個位置:
然後點選「新增專案」:
將專案命名為“GA4 API haranhuang”,然後點擊「建立」:
啟用Google Analytics Data API
現將Google Cloud的專案切換為剛建立的「GA4 API haranhuang」:
點擊右上角的導航選單,然後點擊「API和服務」——「已啟用的API和服務」——「+啟用API和服務』,搜尋“Google Analytics Data API”,這個是GA4資料報告的API,將它啟用:
建立服務帳號
點擊右上角的導航選單,然後點擊「API和服務」——「憑證」
就可以看到憑證的管理介面:
點選「+建立憑證」-「服務帳號」
服務帳號命名為“GA4 API TEST”,其他位置預設的就可以,然後點選“完成”
就可以看到:
注意這個郵箱,後面會需要在GA4裡授權。
下載JSON秘鑰
點選開啟服務帳號:
然後點選「金鑰」-「新增鍵」-「建立新的金鑰」,選擇JSON:
點擊“創建”,可以看到下載了一個秘鑰:
取得GA4授權
給服務帳號ga4-api-test@ga4-api-haranhuang.iam.gserviceaccount.com授權,在GA4裡點擊「管理」-「資源存取權管理」-「+」-「新增使用者」,將其新增,權限類型是「檢視者」的就可以
Python裡
安裝基礎庫
pip install google-analytics-data
示例程式
#!/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.
"""<a href="https://www.haranhuang.com/tag/google-analytics-data-api" title="查看更多关于Google Analytics Data API的文章" target="_blank">Google Analytics Data API</a> sample quickstart application.
This application demonstrates the usage of the Analytics Data API using
service account credentials from a JSON file downloaded from
the Google Cloud Console.
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_json_credentials.py
"""
# [START analyticsdata_json_credentials_quickstart]
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
def sample_run_report(property_id="297139614", credentials_json_path="/home/haran_huang/cloudshell_open/python-docs-samples/google-analytics-data/ga4-api-haranhuang-1ff3b44ca9f3.json"):
"""Runs a simple report on a <a href="https://www.haranhuang.com/tag/google-analytics-4" title="查看更多关于Google Analytics 4的文章" target="_blank">Google Analytics 4</a> property."""
# TODO(developer): Uncomment this variable and replace with your
# <a href="https://www.haranhuang.com/tag/google-analytics-4" title="查看更多关于Google Analytics 4的文章" target="_blank">Google Analytics 4</a> property ID before running the sample.
# property_id = "YOUR-<a href="https://www.haranhuang.com/tag/ga4" title="查看更多关于GA4的文章" target="_blank">GA4</a>-PROPERTY-ID"
# [START analyticsdata_json_credentials_initialize]
# TODO(developer): Uncomment this variable and replace with a valid path to
# the credentials.json file for your service account downloaded from the
# Cloud Console.
# credentials_json_path = "/path/to/credentials.json"
# Explicitly use service account credentials by specifying
# the private key file.
client = BetaAnalyticsDataClient.from_service_account_json(credentials_json_path)
# [END analyticsdata_json_credentials_initialize]
# [START analyticsdata_json_credentials_run_report]
request = RunReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name="city")],
metrics=[Metric(name="totalUsers")],
date_ranges=[DateRange(start_date="2025-02-01", end_date="today")],
)
response = client.run_report(request)
# [END analyticsdata_json_credentials_run_report]
print("Report result:")
for row in response.rows:
print(row.dimension_values[0].value, row.metric_values[0].value)
# [END analyticsdata_json_credentials_quickstart]
if __name__ == "__main__":
sample_run_report()
這個程式的作用是獲取,2月起,每個城市的总使用者人数。
將Property ID和秘鑰替換成你自己的:
運行後资料如下: