API কুইকস্টার্ট

এই পৃষ্ঠাটি আপনাকে দেখায় কিভাবে ক্লায়েন্ট লাইব্রেরি ব্যবহার করে আপনার প্রিয় প্রোগ্রামিং ভাষায় Google Analytics ডেটা API v1 দিয়ে শুরু করবেন।

ধাপ 1. API সক্ষম করুন

একটি নতুন ক্লাউড প্ল্যাটফর্ম প্রকল্প তৈরি করতে এই বোতামটি ক্লিক করুন, স্বয়ংক্রিয়ভাবে Google Analytics ডেটা API v1 সক্ষম করুন এবং এই টিউটোরিয়ালের জন্য প্রয়োজনীয় পরিষেবা অ্যাকাউন্ট তৈরি করুন:

Google Analytics ডেটা API v1 সক্ষম করুন৷

ফলস্বরূপ ডায়ালগে ক্লিক করুন ক্লায়েন্ট কনফিগারেশন ডাউনলোড করুন এবং ফাইল credentials.json আপনার কাজের ডিরেক্টরিতে সংরক্ষণ করুন।

ধাপ 2. Google Analytics 4 প্রপার্টিতে পরিষেবা অ্যাকাউন্ট যোগ করুন

একটি টেক্সট এডিটর ব্যবহার করে, পূর্ববর্তী ধাপে ডাউনলোড করা credentials.json ফাইলটি খুলুন এবং পরিষেবা অ্যাকাউন্টের ইমেল ঠিকানা পেতে client_email ক্ষেত্র অনুসন্ধান করুন যা দেখতে একই রকম:

quickstart@PROJECT-ID.iam.gserviceaccount.com

আপনি Google Analytics ডেটা API v1 এর মাধ্যমে অ্যাক্সেস করতে চান এমন Google Analytics 4 প্রপার্টিতে একজন ব্যবহারকারী যোগ করতে এই ইমেল ঠিকানাটি ব্যবহার করুন। এই টিউটোরিয়ালের জন্য শুধুমাত্র দর্শকের অনুমতি প্রয়োজন।

ধাপ 3. প্রমাণীকরণ কনফিগার করুন

এই অ্যাপ্লিকেশনটি পরিষেবা অ্যাকাউন্টের শংসাপত্রগুলি ব্যবহার করে Google Analytics ডেটা API v1-এর ব্যবহার প্রদর্শন করে৷

আপনার অ্যাপ্লিকেশনের জন্য পরিষেবা অ্যাকাউন্ট শংসাপত্র তৈরি এবং সেট করার নির্দেশাবলীর জন্য আরও পড়ুন

পরিষেবা অ্যাকাউন্টের শংসাপত্রগুলি প্রদান করার একটি সহজ উপায় হল GOOGLE_APPLICATION_CREDENTIALS এনভায়রনমেন্ট ভেরিয়েবল সেট করা, API ক্লায়েন্ট পরিষেবা অ্যাকাউন্ট কী JSON ফাইলটি খুঁজে পেতে এই ভেরিয়েবলের মান ব্যবহার করবে৷

এই উদাহরণে অ্যাপ্লিকেশন শংসাপত্র সেট করতে, নিম্নলিখিত কমান্ডটি চালান এবং ধাপ 1 এ ডাউনলোড করা পরিষেবা অ্যাকাউন্ট JSON ফাইলের পথটি ব্যবহার করুন:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

উদাহরণ স্বরূপ:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/credentials.json"

ধাপ 4. ক্লায়েন্ট লাইব্রেরি ইনস্টল করুন

একটি API কল করুন

এখন আপনি Google Analytics 4 প্রপার্টি অনুসন্ধান করতে Google Analytics ডেটা API ব্যবহার করতে পারেন। API-তে আপনার প্রথম কল করতে নিম্নলিখিত কোডটি চালান:

জাভা

import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.DateRange;
import com.google.analytics.data.v1beta.Dimension;
import com.google.analytics.data.v1beta.Metric;
import com.google.analytics.data.v1beta.Row;
import com.google.analytics.data.v1beta.RunReportRequest;
import com.google.analytics.data.v1beta.RunReportResponse;

/**
 * Google Analytics Data API sample quickstart application.
 *
 * <p>This application demonstrates the usage of the Analytics Data API using service account
 * credentials.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.QuickstartSample"
 * }</pre>
 */
public class QuickstartSample {

  public static void main(String... args) throws Exception {
    /**
     * TODO(developer): Replace this variable with your Google Analytics 4 property ID before
     * running the sample.
     */
    String propertyId = "YOUR-GA4-PROPERTY-ID";
    sampleRunReport(propertyId);
  }

  // This is an example snippet that calls the Google Analytics Data API and runs a simple report
  // on the provided GA4 property id.
  static void sampleRunReport(String propertyId) throws Exception {
    // Using a default constructor instructs the client to use the credentials
    // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {

      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("city"))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .addDateRanges(DateRange.newBuilder().setStartDate("2020-03-31").setEndDate("today"))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);

      System.out.println("Report result:");
      // Iterate through every row of the API response.
      for (Row row : response.getRowsList()) {
        System.out.printf(
            "%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue());
      }
    }
  }
}

পাইথন

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    DateRange,
    Dimension,
    Metric,
    RunReportRequest,
)


def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a simple report on a Google Analytics 4 property."""
    # TODO(developer): Uncomment this variable and replace with your
    #  Google Analytics 4 property ID before running the sample.
    # property_id = "YOUR-GA4-PROPERTY-ID"

    # Using a default constructor instructs the client to use the credentials
    # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = BetaAnalyticsDataClient()

    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="city")],
        metrics=[Metric(name="activeUsers")],
        date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],
    )
    response = client.run_report(request)

    print("Report result:")
    for row in response.rows:
        print(row.dimension_values[0].value, row.metric_values[0].value)


Node.js

  /**
   * TODO(developer): Uncomment this variable and replace with your
   *   Google Analytics 4 property ID before running the sample.
   */
  // propertyId = 'YOUR-GA4-PROPERTY-ID';

  // Imports the Google Analytics Data API client library.
  const {BetaAnalyticsDataClient} = require('@google-analytics/data');

  // Using a default constructor instructs the client to use the credentials
  // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  // Runs a simple report.
  async function runReport() {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dateRanges: [
        {
          startDate: '2020-03-31',
          endDate: 'today',
        },
      ],
      dimensions: [
        {
          name: 'city',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });

    console.log('Report result:');
    response.rows.forEach(row => {
      console.log(row.dimensionValues[0], row.metricValues[0]);
    });
  }

  runReport();

.নেট

using Google.Analytics.Data.V1Beta;
using System;

namespace AnalyticsSamples
{
    class QuickStart
    {
        static void SampleRunReport(string propertyId="YOUR-GA4-PROPERTY-ID")
        {
            /**
             * TODO(developer): Uncomment this variable and replace with your
             *  Google Analytics 4 property ID before running the sample.
             */
            // propertyId = "YOUR-GA4-PROPERTY-ID";

            // Using a default constructor instructs the client to use the credentials
            // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
            BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create();

            // Initialize request argument(s)
            RunReportRequest request = new RunReportRequest
            {
                Property = "properties/" + propertyId,
                Dimensions = { new Dimension{ Name="city"}, },
                Metrics = { new Metric{ Name="activeUsers"}, },
                DateRanges = { new DateRange{ StartDate="2020-03-31", EndDate="today"}, },
            };

            // Make the request
            var response = client.RunReport(request);

            Console.WriteLine("Report result:");
            foreach(Row row in response.Rows)
            {
                Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value);
            }
        }
        static int Main(string[] args)
        {
            SampleRunReport();
            return 0;
        }
    }
}

পিএইচপি

require 'vendor/autoload.php';

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\RunReportRequest;

/**
 * TODO(developer): Replace this variable with your Google Analytics 4
 *   property ID before running the sample.
 */
$property_id = 'YOUR-GA4-PROPERTY-ID';

// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
$client = new BetaAnalyticsDataClient();

// Make an API call.
$request = (new RunReportRequest())
    ->setProperty('properties/' . $property_id)
    ->setDateRanges([
        new DateRange([
            'start_date' => '2020-03-31',
            'end_date' => 'today',
        ]),
    ])
    ->setDimensions([new Dimension([
            'name' => 'city',
        ]),
    ])
    ->setMetrics([new Metric([
            'name' => 'activeUsers',
        ])
    ]);
$response = $client->runReport($request);

// Print results of an API call.
print 'Report result: ' . PHP_EOL;

foreach ($response->getRows() as $row) {
    print $row->getDimensionValues()[0]->getValue()
        . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}

অভিনন্দন! আপনি Google Analytics ডেটা API-তে আপনার প্রথম অনুরোধ পাঠিয়েছেন।