Google Analytics Data API を用いてGA4プロパティから日別のページビュー数を取得する - C#

Google Analytics Data API を用いてGA4プロパティから日別のPVを取得するコードを紹介します。

事前準備: APIの設定

Google Analytics APIのセットアップやサービスアカウントのキーの取得が必要です。 手順の詳細はこちらの記事を参照してください。

事前準備: Google Analytics v4 プロパティのIDの確認

コードに記述する、Google Analytics v4 プロパティのIDを調べます。
Google Analytics の管理画面にアクセスし、Google Analytics V4の[プロパティ設定]画面の[プロパティID]の番号を控えておきます。

プログラム

Windows Formアプリケーションを作成します。

事前準備: Google Analytics Data API ライブラリのインストール

作成したプロジェクトにGoogle Analytics Data APIライブラリをインストールします。インストール手順はこちらの記事を参照して下さい。

UI

下図のフォームを作成します。
ボタンと複数行のテキストボックスを配置します。

コード

以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Analytics.Data.V1Beta;
using Google.Api.Gax;

namespace QuickStart
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
      BetaAnalyticsDataClient aadc;

      BetaAnalyticsDataClientBuilder aadcb = new BetaAnalyticsDataClientBuilder();
      aadcb.CredentialsPath = "(サービスアカウントのキーファイル名)";
      aadc = aadcb.Build();

      RunReportRequest request = new RunReportRequest();
      request.Property = "properties/(プロパティのID番号)";
      
      Dimension dim = new Dimension();
      dim.Name = "Date";
      request.Dimensions.Add(dim);

      Metric met = new Metric();
      met.Name = "screenPageViews";
      request.Metrics.Add(met);

      DateRange dr = new DateRange();
      dr.StartDate = "2021-01-01";
      dr.EndDate = "2021-01-07";
      request.DateRanges.Add(dr);

      RunReportResponse response = aadc.RunReport(request);

      foreach (Row r in response.Rows) {
        textBox1.Text += string.Format("{0}, {1}\r\n", r.DimensionValues[0].Value, r.MetricValues[0].Value);
      }
    }

  }
}

解説

アカウントキーやプロパティの指定についてはこちらの記事を参照してください。
  BetaAnalyticsDataClient aadc;

  BetaAnalyticsDataClientBuilder aadcb = new BetaAnalyticsDataClientBuilder();
  aadcb.CredentialsPath = "(サービスアカウントのキーファイル名)";
  aadc = aadcb.Build();

  RunReportRequest request = new RunReportRequest();
  request.Property = "properties/(プロパティのID番号)";

今回の例では、日別のページビュー数を取得するため、Dimensionには日付である "Date" を指定します。 取得する値はページビューですので、MetricのNameは "screenPageViews" を指定します。
  Dimension dim = new Dimension();
  dim.Name = "Date";
  request.Dimensions.Add(dim);

  Metric met = new Metric();
  met.Name = "screenPageViews";
  request.Metrics.Add(met);

データを取得する期間を選択します。今回の例では、2021年1月1日から2021年1月7日までを期間と指定設定しています。
  DateRange dr = new DateRange();
  dr.StartDate = "2021-01-01";
  dr.EndDate = "2021-01-07";
  request.DateRanges.Add(dr);

RunReportメソッドを呼び出して、GA4からデータを取得します。
  RunReportResponse response = aadc.RunReport(request);

取得したデータをテキストボックスに表示します。
  foreach (Row r in response.Rows) {
    textBox1.Text += string.Format("{0}, {1}\r\n", r.DimensionValues[0].Value, r.MetricValues[0].Value);
  }

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリックします。Google Analytics 4のプロパティから値が取得でき、日別のPVの値がテキストボックスに表示されました。


Google Analytcs 4から日別のPVを取得できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-03-24
作成日: 2021-03-04
iPentec all rights reserverd.