एसिंक्रोनस अनुरोध

Search Ads 360 Reporting API का नया वर्शन अब उपलब्ध है. एपीआई के नए वर्शन में, कस्टम रिपोर्ट बनाने और डेटा को रिपोर्टिंग ऐप्लिकेशन और प्रोसेस में इंटिग्रेट करने की सुविधा मिलती है. Search Ads 360 Reporting API के नए वर्शन पर माइग्रेट करने और उसका इस्तेमाल करने के बारे में ज़्यादा जानें.

बड़ी रिपोर्ट के अनुरोध जनरेट होने में कुछ समय लग सकता है, इसलिए Search Ads 360 API, रिपोर्ट का अनुरोध करने और उन्हें डाउनलोड करने के लिए, एसिंक्रोनस तकनीक का इस्तेमाल करता है. इस तकनीक की मदद से, आपको एक शुरुआती अनुरोध भेजा जाता है, जिसमें उस डेटा के बारे में बताया जाता है जो आपको रिपोर्ट में चाहिए. इसके बाद, Search Ads 360 से रिपोर्ट जनरेट होने तक, आपको पोल के लिए अन्य अनुरोध भेजने होते हैं. रिपोर्ट के साइज़ के आधार पर, Search Ads 360 डेटा को कई फ़ाइलों में बांट देता है. रिपोर्ट जनरेट हो जाने के बाद, आपको हर रिपोर्ट फ़ाइल को डाउनलोड करने के लिए अनुरोध भेजना होता है. अगर कम डेटा का अनुरोध किया जा रहा है, तो सिर्फ़ एक सिंक्रोनस अनुरोध भेजा जा सकता है.

एसिंक्रोनस अनुरोध करने के लिए

  1. आपको रिपोर्ट में किस तरह का डेटा चाहिए, यह बताने के लिए Reports.request() को कॉल करें. अनुरोध किए जा सकने वाले डेटा टाइप के लिए, रिपोर्ट के टाइप देखें.

    Search Ads 360, अनुरोध की पुष्टि करता है और रिपोर्ट आईडी दिखाता है. यह इस अनुरोध के लिए एक यूनीक आइडेंटिफ़ायर होता है.

  2. रिपोर्ट आईडी के साथ Reports.get() को कॉल करें.

    Search Ads 360 से मिले जवाब से पता चलता है कि:

    • रिपोर्ट डाउनलोड के लिए तैयार है या नहीं.
    • अगर रिपोर्ट तैयार है, तो रिपोर्ट डाउनलोड करने के लिए एक या एक से ज़्यादा यूआरएल.
  3. कोड में बदली गई रिपोर्ट फ़ाइलों को डाउनलोड करने के लिए, Reports.getFile() को कॉल करें या सिर्फ़ यूआरएल से सीधे डाउनलोड करें.

    Search Ads 360, रिपोर्ट को UTF-8 कोड में बदली गई फ़ाइल में दिखाता है.

मैं कितने समय में पोल की रिपोर्ट देखकर पता लगाऊं कि वे तैयार हैं या नहीं?

Search Ads 360 को रिपोर्ट जनरेट करने में लगने वाला समय इस बात पर निर्भर करता है कि रिपोर्ट में कितना डेटा मौजूद है. रिपोर्ट की स्थिति जानने के लिए, हर मिनट में एक बार पोल कराने की कोशिश करें. इसके बाद, अगर आपकी रिपोर्ट के अनुरोध की प्रोसेस को पूरा करने में ज़्यादा या कम समय लगता है, तो फ़्रीक्वेंसी में बदलाव करें.

एसिंक्रोनस रिपोर्ट को कई फ़ाइलों में बांटना

एसिंक्रोनस अनुरोध के जवाब में, Search Ads 360 बड़ी रिपोर्ट को अपने-आप कई फ़ाइलों में बांट देता है. फ़ाइल का ज़्यादा से ज़्यादा साइज़ तय करने के लिए, Reports.request.maxRowsPerFile प्रॉपर्टी का इस्तेमाल करें. नतीजे के तौर पर मिलने वाली हर रिपोर्ट फ़ाइल में ज़्यादा से ज़्यादा maxRowsPerFile रिपोर्ट पंक्तियां होनी चाहिए (इसमें हेडर शामिल नहीं होते). हर फ़ाइल के लिए एक अलग यूआरएल जनरेट किया जाता है और Reports.get() के जवाब में दिखाया जाता है. रिपोर्ट फ़ाइलें डाउनलोड करने के बारे में जानकारी के लिए, रिपोर्ट डाउनलोड करना देखें.

CSV रिपोर्ट के लिए, हेडर को हर फ़ाइल में दोहराया जाता है.

ध्यान दें: यह एपीआई, एसिंक्रोनस अनुरोधों के लिए, पेजिंग की सुविधा नहीं देता. इसका मतलब है कि आप यह तय नहीं कर सकते कि आपको किन पंक्तियों में रिपोर्ट फ़ाइलें सेव करनी हैं. फ़ाइलों के बीच लाइनों को बांटने का तरीका अपनी पसंद के मुताबिक होता है. साथ ही, एक ही रिपोर्ट को फिर से चलाने पर, इसमें बदलाव भी हो सकता है.

एसिंक्रोनस उदाहरण

नीचे एसिंक्रोनस तकनीक का इस्तेमाल करने वाले अनुरोधों और जवाबों के उदाहरण दिए गए हैं.

JSON

POST  https://www.googleapis.com/doubleclicksearch/v2/reports
Authorization: Bearer your OAuth 2.0 access token
Content-type: application/json

{
  "reportScope": {
    "agencyId": "12300000000000456", // Replace with your ID
    "advertiserId": "21700000000011523", // Replace with your ID
  },
  "reportType": "keyword",              // This report covers all keywords in the
                                        // advertiser specified in reportScope.
  "columns": [
    { "columnName": "campaignId" },     // Here are some attribute columns available for keyword
    { "columnName": "keywordText" },    // reports.
    { "columnName": "keywordLandingPage" },

    { "columnName": "date" },           // The date column segments the report by individual days.

    { "columnName": "dfaRevenue" },     // Here are some metric columns available for keyword
    {                                   // reports
      "columnName": "visits",
      "startDate": "2013-01-01",        // Each metric column can optionally specify its own start
      "endDate": "2013-01-31",          // and end date; by default the report timeRange is used.
      "headerText": "visits last month" // Every column can optionally specify a headerText, which
                                        // changes the name of the column in the report.
    }
  ],
  "timeRange" : {
    "startDate" : "2012-05-01",         // Dates are inclusive and specified in YYYY-MM-DD format.
    "endDate" : "2012-05-02"

    // Alternatively, try the "changedMetricsSinceTimestamp" or "changedAttributesSinceTimestamp"
    // options. See Incremental reports.

  },
  "filters": [
    {
      "column" : { "columnName": "keywordLandingPage" },
      "operator" : "startsWith",
      "values" : [                      // With this filter, only keywords with landing pages
        "http://www.foo.com",           // rooted at www.foo.com or www.bar.com are returned.
        "http://www.bar.com"            // See Filtered reports.
      ]
    }
  ],
  "downloadFormat": "csv",
  "maxRowsPerFile": 6000000,            // Required. See Splitting reports into multiple files.
  "statisticsCurrency": "agency",       // Required. See Currency for statistics.
  "verifySingleTimeZone": false,        // Optional. Defaults to false. See Time zone.
  "includeRemovedEntities": false           // Optional. Defaults to false.
}
          

Java

/**
 * Creates a campaign report request, submits the report, and returns the report ID.
 */
private static String createReport(Doubleclicksearch service) throws IOException {
  try {
     return service.reports().request(createSampleRequest()).execute().getId();
  } catch (GoogleJsonResponseException e) {
    System.err.println("Report request was rejected.");
    for (ErrorInfo error : e.getDetails().getErrors()) {
      System.err.println(error.getMessage());
    }
    System.exit(e.getStatusCode());
    return null; // Unreachable code.
  }
}

/**
 * Creates a simple static request that lists the ID and name of all
 * campaigns under agency 12300000000000456 and advertiser 21700000000011523.
 * Substitute your own agency ID and advertiser IDs for the IDs in this sample.
 */
private static ReportRequest createSampleRequest() {
  return new ReportRequest()
      .setReportScope(new ReportScope()
          .setAgencyId(12300000000000456L) // Replace with your ID
          .setAdvertiserId(21700000000011523L)) // Replace with your ID
      .setReportType("campaign")
      .setColumns(Arrays.asList(
          new ReportApiColumnSpec[] {
            new ReportApiColumnSpec().setColumnName("campaignId"),
            new ReportApiColumnSpec().setColumnName("campaign")
          }))
      .setTimeRange(new TimeRange()
          .setStartDate("2012-05-01")
          .setEndDate("2012-05-01"))
      .setDownloadFormat("csv")
      .setStatisticsCurrency("usd")
      .setMaxRowsPerFile(5000000);
}

.NET

यह फ़ंक्शन एक रिपोर्ट बनाता है, जिसमें किसी विज्ञापन देने वाले के कैंपेन की सूची होती है. साथ ही, रिस्पॉन्स के तौर पर मिला टोकन reportId को असाइन करता है.
using api = Google.Apis.Doubleclicksearch.v2;

/// <summary>
/// Creates a report with a sample request and returns the report ID.
/// </summary>
/// <param name="service">Search Ads 360 API service.</param>
private static string CreateReport(api.DoubleclicksearchService service)
{

    var req = service.Reports.Request(CreateSampleRequest());
    var report = req.Execute();
    Console.WriteLine("Created report: ID={0}", report.Id);
    return report.Id;
}

/// <summary>
/// Returns a simple static request that lists the ID and name of all
/// campaigns under an advertiser.
/// Substitute your own agency ID and advertiser IDs for the IDs in this sample.
/// </summary>
private static api.Data.ReportRequest CreateSampleRequest()
{
    return new api.Data.ReportRequest
    {
        ReportScope = new api.Data.ReportRequest.ReportScopeData
        {
            AgencyId = 12300000000000456, // Replace with your ID
            AdvertiserId = 21700000000011523 // Replace with your ID
        },
        ReportType = ReportType.CAMPAIGN,
        Columns = new List<api.Data.ReportApiColumnSpec>
        {
            new api.Data.ReportApiColumnSpec
            {
                ColumnName = "campaignId",
            },
            new api.Data.ReportApiColumnSpec
            {
                ColumnName = "campaign",
            },
        },
        TimeRange = new api.Data.ReportRequest.TimeRangeData
        {
            StartDate = "2015-01-01",
            EndDate = "2015-01-07",
        },
        DownloadFormat = "csv",
        StatisticsCurrency = "usd",
        MaxRowsPerFile = 5000000,
    };
}

Python

def request_report(service):
  """Request sample report and print the report ID that DS returns. See Set Up Your Application.

  Args:
    service: An authorized Doubleclicksearch service.
  Returns:
    The report id.
  """
  request = service.reports().request(
      body=
      {
        "reportScope": {
            "agencyId": "12300000000000456", // Replace with your ID
            "advertiserId": "21700000000011523", // Replace with your ID
            "engineAccountId": "700000000073991" // Replace with your ID
            },
        "reportType": "keyword",
        "columns": [
            { "columnName": "campaignId" },
            { "columnName": "keywordText" },
            { "columnName": "keywordLandingPage" },

            { "columnName": "date" },

            { "columnName": "dfaRevenue" },
            {
              "columnName": "visits",
              "startDate": "2013-01-01",
              "endDate": "2013-01-31",
              "headerText": "visits last month"
            }
          ],
          "timeRange" : {
            "startDate" : "2012-05-01",
            "endDate" : "2012-05-02"
          },
          "filters": [
            {
              "column" : { "columnName": "keywordLandingPage" },
              "operator" : "startsWith",
              "values" : [
                "http://www.foo.com",
                "http://www.bar.com"
              ]
            }
          ],
          "downloadFormat": "csv",
          "maxRowsPerFile": 6000000,
          "statisticsCurrency": "agency",
          "verifySingleTimeZone": "false",
          "includeRemovedEntities": "false"
        }
  )

  json_data = request.execute()
  return json_data['id']

अगर पुष्टि हो जाती है

अगर रिपोर्ट की पुष्टि हो जाती है, तो Search Ads 360 एक रिपोर्ट आईडी दिखाता है. Search Ads 360, मुद्रा कोड और टाइम ज़ोन के बारे में मेटाडेटा भी दिखाता है.

{
  "kind": "adsdartsearch#report",
  "id": "MTMyNDM1NDYK",                      // This is the report id.
  "isReportReady": false,                    // The report is not finished generating.

  "request": {                               // The request that created this report.
    ...
  },

  "statisticsCurrencyCode": "CAD",           // The currency used for statistics. E.g., if
                                             // advertiser currency was requested, this would be
                                             // currency code of the advertiser in scope.

  "statisticsTimeZone": "America/New_York"   // If all statistics in the report were sourced from
                                             // a single time zone, this would be it. If
                                             // verifySingleTimeZone was set to true in the request,
                                             // then this field will always be populated (or the
                                             // request will fail).
}
      

अगर पुष्टि नहीं हो पाती है

अगर रिपोर्ट की पुष्टि नहीं हो पाती है, तो Search Ads 360 गड़बड़ी ऑब्जेक्ट के साथ एचटीटीपी 400 रिस्पॉन्स दिखाता है. उदाहरण के लिए, ऊपर दिए गए उदाहरण में, किसी असली एजेंसी के बारे में नहीं बताया गया है:

{
 "error": {
   "code": 400,
   "message": "statisticsCurrency: the agency in scope does not have a valid currency. Please make sure the agency is properly initialized in Search Ads 360."
 }
}

रिपोर्ट की स्थिति के लिए पोल

रिपोर्ट आईडी के साथ Report.Get() को कॉल करें.

JSON

GET https://www.googleapis.com/doubleclicksearch/v2/reports/MTMyNDM1NDYK
          

Java

/**
 * Polls the reporting API with the reportId until the report is ready.
 * Returns the report.
 */
private static Report pollUntilReportIsFinished(Doubleclicksearch service, String reportId)
    throws IOException, InterruptedException {
  long delay = 1;
  while (true) {
    Report report = null;
    try {
      report = service.reports().get(reportId).execute();
    } catch (GoogleJsonResponseException e) {
      System.err.println("Report generation has failed.");
      System.exit(e.getStatusCode());
    }
    if (report.getIsReportReady()) {
      return report;
    }
    System.out.format("Report %s is not ready - waiting %s seconds.%n", reportId, delay);
    Thread.sleep(TimeUnit.SECONDS.toMillis(delay));
    delay = delay + delay; // Double the delay for the next iteration.
  }
}

.NET

using api = Google.Apis.Doubleclicksearch.v2;

/// <summary>
/// Polls until the report with the given ID completes.
/// </summary>
/// <param name="service">Search Ads 360 API service.</param>
/// <param name="reportId">Report ID to poll.</param>
/// <exception cref="ApplicationException">
/// Thrown when the report completes, but has failed.
/// </exception>
private static api.Data.Report PollUntilReportIsFinished(
    api.DoubleclicksearchService service,
    string reportId)
{
    TimeSpan delay = TimeSpan.FromSeconds(1);
    while (true)
    {
        api.Data.Report report;
        try
        {
            report = service.Reports.Get(reportId).Execute();
        }
        catch (Google.GoogleApiException ex)
        {
            throw new ApplicationException("Report generation failed", ex);
        }
        if (report.IsReportReady.GetValueOrDefault(false))
        {
            return report;
        }
        Console.WriteLine("Report is not ready - waiting {0}", delay);
        Thread.Sleep(delay);
        delay = delay.Add(delay); // Double the delay for the next iteration.
    }
}

Python

import pprint
import simplejson
from googleapiclient.errors import HttpError

def poll_report(service, report_id):
  """Poll the API with the reportId until the report is ready, up to ten times.

  Args:
    service: An authorized Doubleclicksearch service.
    report_id: The ID DS has assigned to a report.
  """
  for _ in xrange(10):
    try:
      request = service.reports().get(reportId=report_id)
      json_data = request.execute()
      if json_data['isReportReady']:
        pprint.pprint('The report is ready.')

        # For large reports, DS automatically fragments the report into multiple
        # files. The 'files' property in the JSON object that DS returns contains
        # the list of URLs for file fragment. To download a report, DS needs to
        # know the report ID and the index of a file fragment.
        for i in range(len(json_data['files'])):
          pprint.pprint('Downloading fragment ' + str(i) + ' for report ' + report_id)
          download_files(service, report_id, str(i)) # See Download the report.
        return

      else:
        pprint.pprint('Report is not ready. I will try again.')
        time.sleep(10)
    except HttpError as e:
      error = simplejson.loads(e.content)['error']['errors'][0]

      # See Response Codes
      pprint.pprint('HTTP code %d, reason %s' % (e.resp.status, error['reason']))
      break

रिपोर्ट तैयार न होने पर

अगर रिपोर्ट तैयार नहीं है, तो Search Ads 360 एचटीटीपी 202 रिस्पॉन्स दिखाता है और isReportReady फ़ील्ड गलत होता है.

{
  "kind": "doubleclicksearch#report",
  "id": "MTMyNDM1NDYK",
  "isReportReady": false,
  "request": {
    ...
  },
  ...
}
      

रिपोर्ट तैयार होने पर

जब रिपोर्ट तैयार हो जाती है और डाउनलोड के लिए तैयार हो जाती है, तब isReportReady फ़ील्ड 'सही' होता है. इस जवाब में files नाम का एक और फ़ील्ड भी होता है, जिसमें रिपोर्ट फ़ाइलों को डाउनलोड करने के लिए यूआरएल होते हैं.

{
  "kind": "doubleclicksearch#report",
  "id": "MTMyNDM1NDYK",
  "isReportReady": true,
  "request": {
    ...
  },
  ...
  "rowCount": 1329,        // Total rows in the report, not counting headers.
  "files": [
    {
      "url": "https://www.googleapis.com/doubleclicksearch/v2/reports/MTMyNDM1NDYK/files/0"
      "byteCount": "10242323"
    },
    {
      "url": "https://www.googleapis.com/doubleclicksearch/v2/reports/MTMyNDM1NDYK/files/1"
      "byteCount": "10242323"
    }
  ],
}
      

अगर रिपोर्ट जनरेट नहीं हो पाती है

अगर Search Ads 360 कोई रिपोर्ट जनरेट नहीं कर पाता, तो यह कई एचटीटीपी गड़बड़ी कोड में से एक को ब्यौरे के साथ दिखाता है.

{
  "error" : {
   "code" : 410,            // Or other error codes.
   "message" : "Processing was halted on the backend and will not continue."
  }
}
      

Search Ads 360 से मिलने वाली गड़बड़ियों की सूची के लिए, रिस्पॉन्स कोड देखें.

रिपोर्ट डाउनलोड करना

रिपोर्ट की हर फ़ाइल के यूआरएल पर सीधे क्लिक करके या रिपोर्ट आईडी और फ़ाइल नंबर (0 इंडेक्स किया गया) के साथ Reports.getFile() को कॉल करके, रिपोर्ट डाउनलोड की जा सकती है. Search Ads 360, रिपोर्ट को UTF-8 कोड में बदली गई फ़ाइल में दिखाता है.

यहां Reports.getFile() अनुरोधों के उदाहरण दिए गए हैं:

JSON

GET https://www.googleapis.com/doubleclicksearch/v2/reports/MTMyNDM1NDYK/files/0?alt=media
और
GET https://www.googleapis.com/doubleclicksearch/v2/reports/MTMyNDM1NDYK/files/1?alt=media
          

Java

/**
 * Downloads the shards of a completed report to the given local directory.
 * Files are named CampaignReport0.csv, CampaignReport1.csv, and so on.
 */
private static void downloadFiles(
    Doubleclicksearch service,
    Report report,
    String localPath) throws IOException {
  for (int i = 0; i < report.getFiles().size(); i++) {
    FileOutputStream outputStream =
        new FileOutputStream(new File(localPath, "CampaignReport" + i));
    service.reports().getFile(report.getId(), i).executeAndDownloadTo(outputStream);
    outputStream.close();
  }
}

.NET

using api = Google.Apis.Doubleclicksearch.v2;

/// <summary>
/// Downloads the shards of a completed report to the given local directory.
/// Files are named CampaignReport0.csv, CampaignReport1.csv, and so on.
/// </summary>
/// <param name="service">Search Ads 360 API service.</param>
/// <param name="report">Report ID to download.</param>
/// <param name="localPath">Path of the directory to place downloaded files.</param>
private static void DownloadFiles(
    api.DoubleclicksearchService service,
    api.Data.Report report,
    string localPath)
{
    Directory.CreateDirectory(localPath);
    for (int i = 0; i < report.Files.Count; ++i)
    {
        string fileName = Path.Combine(
            localPath,
            string.Format("CampaignReport{0}.csv", i));
        Console.WriteLine("Downloading shard {0} to {1}", i, fileName);
        using (Stream dst = File.OpenWrite(fileName))
        {
            service.Reports.GetFile(report.Id, i).Download(dst);
        }
    }
}

Python

def download_files(service, report_id, report_fragment):
  """Generate and print sample report.

  Args:
    service: An authorized Doubleclicksearch service.
    report_id: The ID DS has assigned to a report.
    report_fragment: The 0-based index of the file fragment from the files array.
  """
  f = file('report-' + report_fragment + '.csv', 'w')
  request = service.reports().getFile_media(reportId=report_id, reportFragment=report_fragment)
  f.write(request.execute().decode('utf-8'))
  f.close()

उदाहरण के तौर पर दी गई रिपोर्ट

यहां CSV रिपोर्ट का उदाहरण दिया गया है. रिपोर्ट के हर फ़्रैगमेंट में अपनी हेडर लाइन होती है. इस फ़ॉर्मैट के बारे में जानने के लिए आरएफ़सी 4180 देखें.

keywordText,campaignId,landingPageUrl,day,revenue,visits last month,my revenue
google,71700000002104742,http://www.google.com,2012-05-01,10.2,5,20
google,71700000002104742,http://www.google.com,2012-05-02,11,10,60.23
      

आईडी की मैपिंग फ़ाइल डाउनलोड करें

उस फ़ाइल को डाउनलोड किया जा सकता है जिसमें Search Ads 360 के पिछले वर्शन और Search Ads 360 के नए वर्शन के बीच आईडी मैपिंग मौजूद हों. विज्ञापन देने वाले जिस व्यक्ति या कंपनी ने अनुरोध किया है उसकी फ़ाइल में, वे सभी चाइल्ड इकाइयां शामिल होती हैं जो Search Ads 360 के पुराने वर्शन और नए वर्शन में मौजूद होती हैं. जैसे, इंजन खाते, कैंपेन, विज्ञापन ग्रुप वगैरह.

Python

def download_mapping_file(service, file_name, agency_id, advertiser_id):
    """Generate and save mapping file to a csv.

    Args:
      service: An authorized Doubleclicksearch service.
      file_name: Filename to write the ID mapping file.
      agency_id: DS ID of the agency.
      advertiser_id: DS ID of the advertiser.
    """
    request = service.reports().getIdMappingFile_media(agencyId=agency_id,
        advertiserId=advertiser_id)

    response = request.execute()
    response = response.decode('utf-8')

    f = open(file_name + '.csv', 'w')
    f.write(response)
    f.close()