LoginSignup
0
4

More than 3 years have passed since last update.

ReportingAPI + Cloud Functionsで各ページのアクセス数を取得

Posted at

目的

ReportingAPI + Cloud Functionsを使用して各ページのアクセス数を取得する方法を記載します。
Google Analyticsのデータ取得にはReporting API v4(google-api-python-client)を使用します。

環境

google-api-python-client: 1.12.2
oauth2client: 4.1.3

流れ

1.Google API Consoleの設定
2.Google Analyticsの設定
3.Analyticsデータの出力

1.Google API Consoleの設定

Google API ConsoleからReporting API v4を有効にします。
この際に秘密鍵をダウンロードしサービスアカウントのメールアドレスを控えておきます。

quickstart@PROJECT-ID.iam.gserviceaccount.com

2.Google Analyticsの設定

Google Analyticsの[管理]>[ユーザー管理を表示]>[ユーザー追加]から先ほどのメールアドレスを追加します。

3.Analyticsデータの出力

GCPのCloud Functionsから関数を作成し、以下のソースを張り付ければ完了
※VIEW_ID、KEY_FILE_LOCATIONの値は自身のものに置き換えてください。

main.py
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'Jsonファイルのパス'
VIEW_ID = 'VIEW_ID'

def initialize_analyticsreporting():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        KEY_FILE_LOCATION, SCOPES)
    analytics = build('analyticsreporting', 'v4', credentials=credentials)
    return analytics

def get_report(analytics):
    return analytics.reports().batchGet(
        body={
            'reportRequests': [
                {
                    'viewId': VIEW_ID,
                    'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
                    'metrics': [{'expression': 'ga:uniquePageviews'}],
                    'dimensions': [{'name': 'ga:pagePath'}]
                }]
        }
    ).execute()

def print_response(response):
    for report in response.get('reports', []):
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get(
            'metricHeader', {}).get('metricHeaderEntries', [])

        for row in report.get('data', {}).get('rows', []):
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])

            for i, values in enumerate(dateRangeValues):
                for dimension, value in zip(dimensions, values.get('values')):
                    print(dimension + ':' + value)


def main(event, context):
    analytics = initialize_analyticsreporting()
    response = get_report(analytics)
    print_response(response)
requirements.txt
google-api-python-client==1.12.2
oauth2client==4.1.3

感想

PythonもGCPもAnalyticsも初心者だったのでいろいろ勉強になりました
今回はブログにランキング機能が欲しくて作ってみましたがFireStoreにアクセス数カウントしてくのとどれくらい料金に差が出るんですかね:thinking:
ReportingAPIやる前にAnalyticsの知識付けたほうがよさそうですね(笑)

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4