Crea ed esegui i report

Utilizzando l'API Ad Manager, puoi creare ed eseguire report interattivi. Per maggiori dettagli sui report interattivi in Ad Manager, consulta Crea un report interattivo. Con i report interattivi puoi:

  • Crea un nuovo report utilizzando l'API e avvia un'esecuzione.
  • Esegui un report esistente che hai creato nella UI di Ad Manager.

Dopo aver avviato l'esecuzione di un report, puoi eseguire il polling dello stato del report e leggere i risultati al termine.

Questa guida spiega come creare un report, avviare un'esecuzione asincrona di un Report, eseguire il polling dello stato Operation restituito, ottenere il nome della risorsa Result dall'Operation completato e recuperare un insieme paginato di risultati Rows.

Prerequisito

Prima di continuare, verifica di avere accesso a una rete Google Ad Manager. Per ottenere l'accesso, consulta Inizia a utilizzare Google Ad Manager e le autorizzazioni dei ruoli utente per i report.

Creare un report

Utilizzando il metodo networks.reports.create, puoi creare un oggetto Report.

L'esempio seguente crea un report che mostra le impressioni di ieri suddivise per elemento pubblicitario:

Java

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

public class SyncCreateReport {

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

  public static void syncCreateReport() throws Exception {
    try (ReportServiceClient reportServiceClient = ReportServiceClient.create()) {
      Report report =
        Report.newBuilder()
            .setDisplayName("My API Report")
            .setReportDefinition(
                ReportDefinition.newBuilder()
                    .addDimensions(Dimension.LINE_ITEM_NAME)
                    .addDimensions(Dimension.LINE_ITEM_ID)
                    .addMetrics(Metric.AD_SERVER_IMPRESSIONS)
                    .setDateRange(DateRange.newBuilder().setRelative(RelativeDateRange.YESTERDAY))
                    .setReportType(ReportType.HISTORICAL)
                    .build())
            .build();
      CreateReportRequest request =
          CreateReportRequest.newBuilder()
              .setParent(NetworkName.of("NETWORK_CODE").toString())
              .setReport(report)
              .build();
      Report response = reportServiceClient.createReport(request);
    }
  }
}

Python

from google.ads import admanager_v1
from google.ads.admanager_v1 import Report


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

    # Initialize request argument(s)
    report = admanager_v1.Report(
        display_name="My API Report",
        report_definition=admanager_v1.ReportDefinition(
            dimensions=[
                Report.Dimension.LINE_ITEM_NAME,
                Report.Dimension.LINE_ITEM_ID,
            ],
            metrics=[
                Report.Metric.AD_SERVER_IMPRESSIONS,
            ],
            date_range=Report.DateRange(
                relative=Report.DateRange.RelativeDateRange.YESTERDAY
            ),
            report_type=Report.ReportType.HISTORICAL,
        )
    )

    
    
    

    request = admanager_v1.CreateReportRequest(
        parent="networks/NETWORK_CODE",
        report=report,
    )

    # Make the request
    response = client.create_report(request=request)

    # Handle the response
    print(response)

.NET

using Google.Ads.AdManager.V1;
using Dimension = Google.Ads.AdManager.V1.Report.Types.Dimesnsion;
using Metric = Google.Ads.AdManager.V1.Report.Types.Metric;

public sealed partial class GeneratedReportServiceClientSnippets
{
    public void CreateReport()
    {
        // Create client
        ReportServiceClient reportServiceClient = ReportServiceClient.Create();
        // Initialize request argument(s)
        string parent = "networks/NETWORK_CODE";
        Report report = new Report
        {
            DisplayName = "My API Report",
            ReportDefinition = new ReportDefinition
            {
                Dimensions = { Dimension.LineItemName, Dimension.LineItemId },
                Metrics = { Metric.AdServerImpressions },
                DateRange = new Report.Types.DateRange
                {
                    Relative = Report.Types.DateRange.Types.RelativeDateRange.Yesterday
                },
                ReportType = Report.Types.ReportType.Historical
            }
        };

        // Make the request
        Report response = reportServiceClient.CreateReport(parent, report);
    }
}

PHP


use Google\Ads\AdManager\V1\Client\ReportServiceClient;
use Google\Ads\AdManager\V1\CreateReportRequest;
use Google\Ads\AdManager\V1\Report\DateRange;
use Google\Ads\AdManager\V1\Report\Dimension;
use Google\Ads\AdManager\V1\Report\Metric;
use Google\Ads\AdManager\V1\Report\DateRange\RelativeDateRange;
use Google\Ads\AdManager\V1\Report;
use Google\Ads\AdManager\V1\ReportDefinition;
use Google\Ads\AdManager\V1\Report\ReportType;

function createReport(): void
{
    $client = new ReportServiceClient();
    $report = (new Report())
        ->setDisplayName('My API Report')
        ->setReportDefinition((new ReportDefinition())
            ->setDimensions([
                Dimension::LINE_ITEM_NAME,
                Dimension::LINE_ITEM_ID
            ])
            ->setMetrics([
                Metric::AD_SERVER_IMPRESSIONS
            ])
            ->setDateRange((new DateRange)
                ->setRelative(RelativeDateRange::YESTERDAY)
            )
            ->setReportType(ReportType::HISTORICAL)
        );

    $request = new CreateReportRequest([
        'parent' => "networks/NETWORK_CODE",
        'report' => $report
    ]);

    $response = $client->createReport($request);
    print_r($response);
}

Ruby

require "google/ads/ad_manager/v1"

def create_report
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Ads::AdManager::V1::ReportService::Rest::Client.new

  report = Google::Ads::AdManager::V1::Report.new(
    display_name: "My API Report",
    report_definition: Google::Ads::AdManager::V1::ReportDefinition.new(
      dimensions: [
        :LINE_ITEM_NAME,
        :LINE_ITEM_ID
      ],
      metrics: [
        :AD_SERVER_IMPRESSIONS
      ],
      date_range: Google::Ads::AdManager::V1::Report::DateRange.new(
        relative: :YESTERDAY
      ),
      report_type: :HISTORICAL
    )
  )

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Ads::AdManager::V1::CreateReportRequest.new(
    parent: 'networks/NETWORK_CODE'
    report: report
  )

  # Call the create_report method.
  result = client.create_report request

  # The returned object is of type Google::Ads::AdManager::V1::Report.
  p result
end

Node.js

const parent = 'networks/NETWORK_CODE';

const report = {
  displayName: 'My API Report',
  reportDefinition: {
    dimensions: ['LINE_ITEM_NAME', 'LINE_ITEM_ID'],
    metrics: ['AD_SERVER_IMPRESSIONS'],
    dateRange: {
      relative: 'YESTERDAY',
    },
    reportType: 'HISTORICAL',
  },
};


// Imports the Admanager library
const {ReportServiceClient} = require('@google-ads/admanager').v1;

// Instantiates a client
const admanagerClient = new ReportServiceClient();

async function callCreateReport() {
  // Construct request
  const request = {
    parent,
    report,
  };

  // Run request
  const response = await admanagerClient.createReport(request);
  console.log(response);
}

callCreateReport();

cURL

Richiesta

curl -X POST -H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
  "report": {
    "displayName": "My API Report",
    "reportDefinition": {
      "dimensions": ["LINE_ITEM_NAME", "LINE_ITEM_ID"],
      "metrics": ["AD_SERVER_IMPRESSIONS"],
      "dateRange": {
        "relative": "YESTERDAY"
      },
      "reportType": "HISTORICAL"
    }
  }
}' \
"https://admanager.googleapis.com/v1/networks/${NETWORK_CODE}/reports"

Risposta

{
  "name": "networks/234093456/reports/4555265029",
  "displayName": "My API Report",
  "reportId": "4555265029",
  "reportDefinition": {
    "dimensions": [
      "LINE_ITEM_NAME",
      "LINE_ITEM_ID"
    ],
    "metrics": [
      "AD_SERVER_IMPRESSIONS"
    ],
    "dateRange": {
      "relative": "YESTERDAY"
    },
    "reportType": "HISTORICAL"
  },
  "visibility": "HIDDEN"
}

Dopo aver creato un report, puoi utilizzare l'reportId restituito per eseguirlo.

Creare un report

Per generare un report, devi disporre dell'ID report. Puoi ottenere un ID report nell'interfaccia utente di Ad Manager tramite l'URL del report. Ad esempio, nell'URL https://admanager.google.com/234093456#reports/interactive/detail/report_id=4555265029 l'ID report è 4555265029.

Puoi anche leggere i report a cui l'utente ha accesso utilizzando il metodo networks.reports.list e ottenere l'ID dal nome della risorsa:

networks/234093456/reports/4555265029

Una volta ottenuto l'ID report, puoi avviare un'esecuzione asincrona del report utilizzando il metodo networks.reports.run. Questo metodo restituisce il nome della risorsa di un'operazione di lunga durata Operation. Tieni presente che nel seguente codice di esempio, REPORT_ID è un segnaposto per l'ID report e NETWORK_CODE è un segnaposto per il tuo codice di rete. Per trovare il codice di rete, consulta Trovare informazioni sull'account 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_ID");
      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_ID",
    )

    # 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_ID");
        // 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;
        }
    }
}

PHP


use Google\Ads\AdManager\V1\Client\ReportServiceClient;
use Google\Ads\AdManager\V1\RunReportRequest;
use Google\Ads\AdManager\V1\RunReportResponse;
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Rpc\Status;

function run_report_sample(string $formattedName): void
{
    // Create a client.
    $reportServiceClient = new ReportServiceClient();

    // Prepare the request message.
    $request = (new RunReportRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        $response = $reportServiceClient->runReport($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

function callSample(): void
{
    $formattedName = ReportServiceClient::reportName('NETWORK_CODE', 'REPORT_ID');

    run_report_sample($formattedName);
}

Ruby

require "google/ads/ad_manager/v1"

def run_report
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Ads::AdManager::V1::ReportService::Rest::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Ads::AdManager::V1::RunReportRequest.new(
    :name => 'networks/NETWORK_CODE/reports/REPORT_ID'
  )

  # Call the run_report method.
  result = client.run_report request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

Node.js

const name = 'networks/NETWORK_CODE/reports/REPORT_ID';

// Imports the Admanager library
const {ReportServiceClient} = require('@google-ads/admanager').v1;

// Instantiates a client
const admanagerClient = new ReportServiceClient();

async function callRunReport() {
  // Construct request
  const request = {
    name,
  };

  // Run request
  const [operation] = await admanagerClient.runReport(request);
  const [response] = await operation.promise();
  console.log(response);
}

callRunReport();

cURL

Richiesta

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

Risposta

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

Esegui il polling dello stato del report

Se utilizzi una libreria client, il codice di esempio della sezione precedente esegue il polling dello stato dell'esecuzione del report Operation agli intervalli consigliati e fornisce il risultato al termine dell'operazione. Per maggiori informazioni sugli intervalli di polling consigliati, consulta networks.reports.run.

Se vuoi un maggiore controllo sul polling, invia una singola richiesta per recuperare lo stato attuale di un report in esecuzione utilizzando il metodo networks.operations.reports.runs.get. Alcune librerie client supportano anche l'impostazione di strategie di polling personalizzate:

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;
}

PHP


$options = [
    'initialPollDelayMillis' => 500, // Initial delay of 500ms
    'pollDelayMultiplier' => 1.5,
    'maxPollDelayMillis' => 30000, // Max poll delay of 30 seconds
    'totalPollTimeoutMillis' => 60 * 60 * 1000, // Total timeout of 1 hour in milliseconds
];

$response = $reportServiceClient->runReport($request);
$response->pollUntilComplete($options);

Ruby

options = {
  initial_delay: 0.5, # Initial delay of 500ms (0.5 seconds)
  multiplier: 1.5,
  max_delay: 30.0, # Max poll delay of 30 seconds
  timeout: 60 * 60 # Total timeout of 1 hour in seconds
}
result = client.run_report request
result.wait_until_done!(retry_policy: options)
if result.response?
  p result.response
else
  puts "No response received."
end

Node.js

const options = {
  initialRetryDelayMillis: 500, // Initial delay of 500ms
  retryDelayMultiplier: 1.5,
  maxRetryDelayMillis: 30, // Max poll delay of 30 seconds
  totalTimeoutMillis: 60 * 60 * 1000 // Total timeout of 1 hour
}

const [operation] = await admanagerClient.runReport(request);
operation.backoffSettings = options;
const [response] = await operation.promise();
console.log(response);

cURL

Richiesta

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

Risposta

{
  "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,
}

Recupera il nome della risorsa del risultato

Al termine dell'esecuzione del report Operation contiene il nome risorsa di 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;

PHP


$response = $reportServiceClient->runReport($request);
$response->pollUntilComplete();

if ($response->operationSucceeded()) {
    $result = $response->getResult();
    // Result name in the format networks/[NETWORK_CODE]/reports/[REPORT_ID]/results/[RESULT_ID]
    $resultName = $result->getReportResult();
}

Ruby

result = client.run_report request

result.wait_until_done!
if result.response?
  # Result name in the format networks/[NETWORK_CODE]/reports/[REPORT_ID]/results/[RESULT_ID]
  p result.response.report_result
else
  puts "No response received."
end

Node.js

// Run request
const [operation] = await admanagerClient.runReport(request);
const [response] = await operation.promise();
// Result name in the format networks/[NETWORK_CODE]/reports/[REPORT_ID]/results/[RESULT_ID]
console.log(response.reportResult);

cURL

Richiesta

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

Risposta

{
  "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"
  }
}

Lettura delle righe dei risultati

La risorsa Result ha un solo metodo, networks.reports.results.fetchRows, per leggere un elenco di righe impaginate. Ogni riga contiene un elenco di valori delle dimensioni e un elenco di valori delle metriche raggruppate. Ogni gruppo contiene il valore della metrica e gli eventuali valori di confronto o indicatori. Per saperne di più sui flag, consulta Utilizzare i flag nel report interattivo (beta).

Per i report senza confronti o suddivisioni dell'intervallo di date, è presente un singolo MetricValueGroup con i valori delle metriche (ad esempio impressioni o clic) per l'intero intervallo di date del report.

L'ordine dei valori delle dimensioni e delle metriche è lo stesso dell'ordine in ReportDefinition di Report.

Di seguito è riportato un esempio JSON di un ReportDefinition e di una risposta fetchRows corrispondente:

Definizione rapporto

{
  "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": {}
}

fetchRows Risposta

{
  "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
}

Se utilizzi una libreria client, la risposta ha un iteratore che richiede in modo differito pagine aggiuntive. Puoi anche utilizzare i parametri pageToken e pageSize. Per informazioni dettagliate su questi parametri, consulta Parametri di query. Se esiste un'altra pagina, la risposta contiene un campo nextPageToken con il token da utilizzare nella richiesta successiva.

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(
        name = "networks/NETWORK_CODE/reports/REPORT_ID/results/RESULT_ID")

    # 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, ReportDataTable.Types.Row> response = reportServiceClient.FetchReportResultRows(name);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (ReportDataTable.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 (ReportDataTable.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<ReportDataTable.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 (ReportDataTable.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;
    }
}

PHP


use Google\Ads\AdManager\V1\Client\ReportServiceClient;
use Google\Ads\AdManager\V1\FetchReportResultRowsRequest;
use Google\Ads\AdManager\V1\FetchReportResultRowsResponse;
use Google\ApiCore\ApiException;

function fetch_report_result_rows_sample(): void
{
    // Create a client.
    $reportServiceClient = new ReportServiceClient();

    // Prepare the request message.
    $request = (new FetchReportResultRowsRequest())
        ->setName('networks/NETWORK_CODE/reports/REPORT_ID/results/RESULT_ID');

    // Call the API and handle any network failures.
    try {
        $response = $reportServiceClient->fetchReportResultRows($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

Ruby

require "google/ads/ad_manager/v1"

def fetch_report_result_rows
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Ads::AdManager::V1::ReportService::Rest::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Ads::AdManager::V1::FetchReportResultRowsRequest.new(
    :name => 'networks/NETWORK_CODE/reports/REPORT_ID/results/RESULT_ID'
  )

  # Call the fetch_report_result_rows method.
  result = client.fetch_report_result_rows request

  # The returned object is of type Gapic::PagedEnumerable. You can iterate
  # over elements, and API calls will be issued to fetch pages as needed.
  result.each do |item|
    # Each element is of type ::Google::Ads::AdManager::V1::Report::DataTable::Row.
    p item
  end
end

Node.js

const name = 'networks/NETWORK_CODE/reports/REPORT_ID/results/RESULT_ID';

// Imports the Admanager library
const {ReportServiceClient} = require('@google-ads/admanager').v1;

// Instantiates a client
const admanagerClient = new ReportServiceClient();

async function callFetchReportResultRows() {
  // Construct request
  const request = {
    name,
  };

  // Run request
  const iterable = admanagerClient.fetchReportResultRowsAsync(request);
  for await (const response of iterable) {
      console.log(response);
  }
}

callFetchReportResultRows();

cURL

Richiesta iniziale

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

Richiesta della pagina successiva

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

Risolvere i problemi relativi a un report

Perché il mio report non viene restituito nell'API?
Assicurati che l'utente Ad Manager per cui esegui l'autenticazione abbia accesso al report interattivo. Puoi leggere i report interattivi solo dall'API Ad Manager.
Perché i risultati dei report sulla mia rete di test sono vuoti?
Le reti di test non pubblicano annunci, pertanto i report sul rendimento non contengono dati.
Perché i risultati del report sulla mia rete di produzione sono vuoti?
L'utente per cui esegui l'autenticazione potrebbe non avere accesso ai dati che stai tentando di inserire nel report. Verifica che le autorizzazioni di ruolo e i team siano impostati correttamente.
Perché i clic o le impressioni totali non corrispondono a quelli del report nell'interfaccia utente?
Le impressioni totali si riferiscono all'intera durata dell'elemento pubblicitario, indipendentemente dall'intervallo di date del report. Se un elemento pubblicitario è ancora in pubblicazione, il valore potrebbe cambiare tra due esecuzioni dello stesso report.