Menjalankan laporan

Anda dapat membuat Laporan interaktif, menjalankan laporan yang ada, dan membaca hasil laporan menggunakan Ad Manager API.

Jika Anda tidak terbiasa dengan pelaporan Interaktif di Ad Manager, lihat Membuat Laporan interaktif untuk mengetahui ringkasan cara menggunakan Laporan interaktif di UI Ad Manager.

Untuk laporan yang kompleks, Anda dapat menggunakan UI Ad Manager untuk memeriksa kompatibilitas dimensi dan metrik. Semua laporan UI dapat dijalankan dengan API.

Panduan ini membahas cara memulai operasi asinkron Report, mengambil status Operation yang ditampilkan, mendapatkan nama resource Result dari Operation yang telah selesai, dan mengambil kumpulan hasil bernomor halaman Rows.

Prasyarat

Sebelum melanjutkan, pastikan Anda memiliki akses ke jaringan Google Ad Manager. Untuk mendapatkan akses, lihat Memulai Google Ad Manager.

Menjalankan laporan

Untuk menjalankan laporan, Anda memerlukan ID laporan. Anda bisa mendapatkan ID laporan di UI Ads Manager melalui URL laporan. Misalnya, di URL https://www.google.com/admanager/234093456#reports/interactive/detail/report_id=4555265029, ID laporan adalah 4555265029.

Anda juga dapat membaca laporan yang dapat diakses pengguna menggunakan metode networks.reports.list dan mendapatkan ID dari nama resource:

networks/234093456/reports/4555265029

Setelah memiliki ID laporan, Anda dapat memulai operasi asinkron laporan menggunakan metode networks.reports.run. Metode ini menampilkan nama resource Operation yang berjalan lama. Perhatikan bahwa dalam contoh kode berikut, [REPORT] adalah placeholder untuk ID laporan dan [NETWORK] adalah placeholder untuk kode jaringan Anda. Untuk menemukan kode jaringan, lihat Menemukan informasi akun Ad Manager.

Java

import com.google.ads.admanager.v1.ReportName;
import com.google.ads.admanager.v1.ReportServiceClient;
import com.google.ads.admanager.v1.RunReportResponse;

public class SyncRunReportReportname {

  public static void main(String[] args) throws Exception {
    syncRunReportReportname();
  }

  public static void syncRunReportReportname() throws Exception {
    try (ReportServiceClient reportServiceClient = ReportServiceClient.create()) {
      ReportName name = ReportName.of("[NETWORK_CODE]", "[REPORT]");
      RunReportResponse response = reportServiceClient.runReportAsync(name).get();
    }
  }
}

Python

from google.ads import admanager_v1


def sample_run_report():
    # Create a client
    client = admanager_v1.ReportServiceClient()

    # Initialize request argument(s)
    request = admanager_v1.RunReportRequest(
        name="networks/[NETWORK_CODE]/reports/[REPORT]",
    )

    # Make the request
    operation = client.run_report(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

.NET

using Google.Ads.AdManager.V1;
using Google.LongRunning;

public sealed partial class GeneratedReportServiceClientSnippets
{
    public void RunReportResourceNames()
    {
        // Create client
        ReportServiceClient reportServiceClient = ReportServiceClient.Create();
        // Initialize request argument(s)
        ReportName name = ReportName.FromNetworkCodeReport("[NETWORK_CODE]", "[REPORT]");
        // Make the request
        Operation<RunReportResponse, RunReportMetadata> response = reportServiceClient.RunReport(name);

        // Poll until the returned long-running operation is complete
        Operation<RunReportResponse, RunReportMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        RunReportResponse result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<RunReportResponse, RunReportMetadata> retrievedResponse = reportServiceClient.PollOnceRunReport(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            RunReportResponse retrievedResult = retrievedResponse.Result;
        }
    }
}

cURL

Permintaan

curl -X POST -H "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://admanager.googleapis.com/v1/networks/${NETWORK_CODE}/reports/{$REPORT_ID}:run"

Respons

{
  "name": "networks/234093456/operations/reports/runs/6485392645",
  "metadata": {
    "@type": "type.googleapis.com/google.ads.admanager.v1.RunReportMetadata",
    "report": "networks/234093456/reports/4555265029"
  }
}

Melakukan polling status laporan

Jika Anda menggunakan library klien, kode contoh di bagian sebelumnya akan melakukan polling status laporan yang dijalankan Operation pada interval yang direkomendasikan dan memberikan hasilnya setelah selesai. Untuk mengetahui informasi selengkapnya tentang interval polling yang direkomendasikan, lihat networks.reports.run.

Jika Anda menginginkan kontrol yang lebih besar atas polling, buat permintaan individual untuk mengambil status saat ini dari laporan yang sedang berjalan menggunakan metode networks.operations.reports.runs.get:

Java

import com.google.ads.admanager.v1.ReportServiceSettings;
import com.google.api.gax.longrunning.OperationalTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.retrying.TimedRetryAlgorithm;
import java.time.Duration;

public class SyncRunReport {

  public static void main(String[] args) throws Exception {
    syncRunReport();
  }

  public static void syncRunReport() throws Exception {
    ReportServiceSettings.Builder reportServiceSettingsBuilder = ReportServiceSettings.newBuilder();
    TimedRetryAlgorithm timedRetryAlgorithm =
        OperationalTimedPollAlgorithm.create(
            RetrySettings.newBuilder()
                .setInitialRetryDelayDuration(Duration.ofMillis(500))
                .setRetryDelayMultiplier(1.5)
                .setMaxRetryDelayDuration(Duration.ofMillis(5000))
                .setTotalTimeoutDuration(Duration.ofHours(24))
                .build());
    reportServiceSettingsBuilder
        .createClusterOperationSettings()
        .setPollingAlgorithm(timedRetryAlgorithm)
        .build();
  }
}

Python

from google.ads import admanager_v1
from google.longrunning.operations_pb2 import GetOperationRequest

def sample_poll_report():
# Run the report
client = admanager_v1.ReportServiceClient()
response = client.run_report(name="networks/[NETWORK_CODE]/reports/[REPORT_ID]")

# Check if the long-running operation has completed
operation = client.get_operation(
    GetOperationRequest(name=response.operation.name))
if(operation.done):
    # If it has completed, then access the result
    run_report_response = admanager_v1.RunReportResponse.deserialize(payload=operation.response.value)

.NET

Operation<RunReportResponse, RunReportMetadata> retrievedResponse =
  reportServiceClient.PollOnceRunReport(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
  // If it has completed, then access the result
  RunReportResponse retrievedResult = retrievedResponse.Result;
}

cURL

Permintaan

curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://admanager.googleapis.com/v1/networks/${NETWORK_CODE}/operations/reports/runs/${OPERATION_ID}"

Respons

{
  "name": "networks/234093456/operations/reports/runs/6485392645",
  "metadata": {
    "@type": "type.googleapis.com/google.ads.admanager.v1.RunReportMetadata",
    "percentComplete": 50,
    "report": "networks/234093456/reports/4555265029"
  },
  "done": false,
}

Mendapatkan nama resource hasil

Setelah laporan dijalankan, Operation akan berisi nama resource Result.

Java

RunReportResponse response = reportServiceClient.runReportAsync(name).get();
// Result name in the format networks/[NETWORK_CODE]/reports/[REPORT_ID]/results/[RESULT_ID]
String resultName = response.getReportResult();

Python

operation = client.run_report(request=request)
response = operation.result()
# Result name in the format networks/[NETWORK_CODE]/reports/[REPORT_ID]/results/[RESULT_ID]
result_name = response.report_result

.NET

Operation<RunReportResponse, RunReportMetadata> response = reportServiceClient.RunReport(request);
// Poll until the returned long-running operation is complete
Operation<RunReportResponse, RunReportMetadata> completedResponse = response.PollUntilCompleted();
RunReportResponse result = completedResponse.Result;
// Result name in the format networks/[NETWORK_CODE]/reports/[REPORT_ID]/results/[RESULT_ID]
string resultName = result.ReportResult;

cURL

Permintaan

curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://admanager.googleapis.com/v1/networks/${NETWORK_CODE}/operations/reports/runs/${OPERATION_ID}"

Respons

{
  "name": "networks/234093456/operations/reports/runs/6485392645",
  "metadata": {
    "@type": "type.googleapis.com/google.ads.admanager.v1.RunReportMetadata",
    "percentComplete": 100,
    "report": "networks/234093456/reports/4555265029"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.ads.admanager.v1.RunReportResponse",
    "reportResult": "networks/234093456/reports/4555265029/results/7031632628"
  }
}

Membaca baris hasil

Resource Result memiliki satu metode, networks.reports.results.fetchRows, untuk membaca daftar baris yang di-pagination. Setiap baris memiliki daftar nilai dimensi dan daftar nilai metrik yang dikelompokkan. Setiap grup berisi nilai metrik dan nilai atau tanda perbandingan. Untuk informasi selengkapnya tentang tanda, lihat Menggunakan tanda dalam laporan interaktif.

Untuk laporan tanpa perbandingan atau pemisahan rentang tanggal, ada satu MetricValueGroup dengan nilai metrik (misalnya, tayangan iklan atau klik) untuk seluruh rentang tanggal laporan.

Urutan nilai dimensi dan metrik sama dengan urutan dalam ReportDefinition Report.

Berikut adalah contoh JSON untuk ReportDefinition dan respons fetchRows yang sesuai:

{
  "name": "networks/234093456/reports/4555265029",
  "visibility": "SAVED",
  "reportId": "4555265029",
  "reportDefinition": {
     "dimensions": [
      "LINE_ITEM_NAME",
      "LINE_ITEM_ID"
    ],
    "metrics": [
      "AD_SERVER_IMPRESSIONS"
    ], 
    "currencyCode": "USD",
    "dateRange": {
      "relative": "YESTERDAY"
    },
    "reportType": "HISTORICAL"
  },
  "displayName": "Example Report",
  "updateTime": "2024-09-01T13:00:00Z",
  "createTime": "2024-08-01T02:00:00Z",
  "locale": "en-US",
  "scheduleOptions": {}
}
{
  "rows": [
    {
      "dimensionValues": [
        {
          "stringValue": "Line Item #1"
        },
        {
          "intValue": "6378470710"
        }
      ],
      "metricValueGroups": [
        {
          "primaryValues": [
            {
              "intValue": "100"
            }
          ]
        }
      ]
    },
    {
      "dimensionValues": [
        {
          "stringValue": "Line Item #2"
        },
        {
          "intValue": "5457147368"
        }
      ],
      "metricValueGroups": [
        {
          "primaryValues": [
            {
              "intValue": "95"
            }
          ]
        }
      ]
    }
],
"runTime": "2024-10-02T10:00:00Z",
  "dateRanges": [
    {
      "startDate": {
        "year": 2024,
        "month": 10,
        "day": 1
      },
      "endDate": {
        "year": 2024,
        "month": 10,
        "day": 1
      }
    }
  ],
  "totalRowCount": 2
}

Jika Anda menggunakan library klien, respons memiliki iterator yang secara lambat meminta halaman tambahan. Anda juga dapat menggunakan parameter pageToken dan pageSize. Untuk mengetahui detail parameter ini, lihat Parameter kueri. Jika ada halaman lain, respons akan berisi kolom nextPageToken dengan token yang akan digunakan dalam permintaan berikutnya.

Java



import com.google.ads.admanager.v1.Report;
import com.google.ads.admanager.v1.ReportServiceClient;

public class SyncFetchReportResultRowsString {

  public static void main(String[] args) throws Exception {
    syncFetchReportResultRowsString();
  }

  public static void syncFetchReportResultRowsString() throws Exception {
    try (ReportServiceClient reportServiceClient = ReportServiceClient.create()) {
      String name = "networks/[NETWORK_CODE]/reports/[REPORT_ID]/results/[RESULT_ID]";
      for (Report.DataTable.Row element :
          reportServiceClient.fetchReportResultRows(name).iterateAll()) {
      }
    }
  }
}

Python

from google.ads import admanager_v1


def sample_fetch_report_result_rows():
    # Create a client
    client = admanager_v1.ReportServiceClient()

    # Initialize request argument(s)
    request = admanager_v1.FetchReportResultRowsRequest(
    )

    # Make the request
    page_result = client.fetch_report_result_rows(request=request)

    # Handle the response
    for response in page_result:
        print(response)

.NET

using Google.Ads.AdManager.V1;
using Google.Api.Gax;
using System;

public sealed partial class GeneratedReportServiceClientSnippets
{
    public void FetchReportResultRows()
    {
        // Create client
        ReportServiceClient reportServiceClient = ReportServiceClient.Create();
        // Initialize request argument(s)
        string name = "";
        // Make the request
        PagedEnumerable<FetchReportResultRowsResponse, Report.Types.DataTable.Types.Row> response = reportServiceClient.FetchReportResultRows(name);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (Report.Types.DataTable.Types.Row item in response)
        {
            // Do something with each item
            Console.WriteLine(item);
        }

        // Or iterate over pages (of server-defined size), performing one RPC per page
        foreach (FetchReportResultRowsResponse page in response.AsRawResponses())
        {
            // Do something with each page of items
            Console.WriteLine("A page of results:");
            foreach (Report.Types.DataTable.Types.Row item in page)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
        }

        // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
        int pageSize = 10;
        Page<Report.Types.DataTable.Types.Row> singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
        foreach (Report.Types.DataTable.Types.Row item in singlePage)
        {
            // Do something with each item
            Console.WriteLine(item);
        }
        // Store the pageToken, for when the next page is required.
        string nextPageToken = singlePage.NextPageToken;
    }
}

cURL

Permintaan awal

curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://admanager.googleapis.com/v1/networks/${NETWORK_CODE}/reports/${REPORT_ID}/results/${RESULT_ID}:fetchRows"

Permintaan halaman berikutnya

curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://admanager.googleapis.com/v1/networks/${NETWORK_CODE}/reports/${REPORT_ID}/results/${RESULT_ID}:fetchRows?pageToken=${PAGE_TOKEN}"

Memecahkan masalah terkait laporan

Mengapa laporan saya tidak ditampilkan di API?
Pastikan pengguna Ad Manager yang Anda autentikasi memiliki akses ke laporan Interaktif. Anda hanya dapat membaca Laporan interaktif dari Ad Manager API.
Mengapa hasil laporan di jaringan pengujian saya kosong?
Jaringan pengujian tidak menayangkan iklan, sehingga laporan penayangan tidak memiliki data.
Mengapa hasil laporan di jaringan produksi saya kosong?
Pengguna yang Anda autentikasi mungkin tidak memiliki akses ke data yang Anda coba laporkan. Pastikan izin peran dan tim mereka ditetapkan dengan benar.
Mengapa klik atau tayangan sepanjang waktu tidak cocok dengan laporan saya di UI?
Tayangan iklan sepanjang waktu adalah untuk seluruh masa aktif item baris, terlepas dari rentang tanggal laporan. Jika item baris masih ditayangkan, nilainya mungkin berubah antara dua pengoperasian laporan yang sama.