Reporting Samples

The code samples below provide examples of common reporting functions using the AdWords API. Client Library.

Download a criteria performance report with selector

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.Util.Reports
Imports Google.Api.Ads.AdWords.v201705
Imports Google.Api.Ads.Common.Util.Reports

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example gets and downloads a criteria Ad Hoc report from an XML
  ''' report definition.
  ''' </summary>
  Public Class DownloadCriteriaReportWithSelector
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New DownloadCriteriaReportWithSelector
      Console.WriteLine(codeExample.Description)
      Try
        Dim fileName As String = "INSERT_OUTPUT_FILE_NAME"
        codeExample.Run(New AdWordsUser, fileName)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example gets and downloads a criteria Ad Hoc report from an XML report" & _
          " definition."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="fileName">The file to which the report is downloaded.
    ''' </param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal fileName As String)
      Dim definition As New ReportDefinition

      definition.reportName = "Last 7 days CRITERIA_PERFORMANCE_REPORT"
      definition.reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT
      definition.downloadFormat = DownloadFormat.GZIPPED_CSV
      definition.dateRangeType = ReportDefinitionDateRangeType.LAST_7_DAYS

      ' Create the selector.
      Dim selector As New Selector
      selector.fields = New String() {"CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria", _
          "FinalUrls", "Clicks", "Impressions", "Cost"}

      selector.predicates = New Predicate() {
        Predicate.In("Status", New String() {"ENABLED", "PAUSED"})
      }

      definition.selector = selector

      ' Optional: Include zero impression rows.
      DirectCast(user.Config, AdWordsAppConfig).IncludeZeroImpressions = True

      ' Optional: You can also skip the report headers, column headers and
      ' report summary etc. to make the report parsing simpler.
      ' DirectCast(user.Config, AdWordsAppConfig).SkipColumnHeader = True
      ' DirectCast(user.Config, AdWordsAppConfig).SkipReportHeader = True
      ' DirectCast(user.Config, AdWordsAppConfig).SkipReportSummary = True

      Dim filePath As String = ExampleUtilities.GetHomeDir() & Path.DirectorySeparatorChar & _
          fileName

      Try
        Dim utilities As New ReportUtilities(user, "v201705", definition)
        Using reportResponse As ReportResponse = utilities.GetResponse()
          reportResponse.Save(filePath)
        End Using
        Console.WriteLine("Report was downloaded to '{0}'.", filePath)
      Catch e As Exception
        Throw New System.ApplicationException("Failed to download report.", e)
      End Try

    End Sub
  End Class
End Namespace

Download a criteria performance report with AWQL

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.Util.Reports
Imports Google.Api.Ads.AdWords.v201705
Imports Google.Api.Ads.Common.Util.Reports

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example gets and downloads a criteria Ad Hoc report from an AWQL
  ''' query. See https://developers.google.com/adwords/api/docs/guides/awql for
  ''' AWQL documentation.
  ''' </summary>
  Public Class DownloadCriteriaReportWithAwql
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New DownloadCriteriaReportWithAwql
      Console.WriteLine(codeExample.Description)
      Try
        Dim fileName As String = "INSERT_OUTPUT_FILE_NAME"
        codeExample.Run(New AdWordsUser, fileName)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example gets and downloads a criteria Ad Hoc report from an AWQL" & _
            " query. See https://developers.google.com/adwords/api/docs/guides/awql for" & _
            " AWQL documentation."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="fileName">The file to which the report is downloaded.
    ''' </param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal fileName As String)
      Dim query As String = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, " & _
          "Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT WHERE Status IN " & _
          "[ENABLED, PAUSED] DURING LAST_7_DAYS"

      Dim filePath As String = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar & _
          fileName

      Try
        Dim utilities As New ReportUtilities(user, "v201705", query, _
                                             DownloadFormat.GZIPPED_CSV.ToString())
        Using reportResponse As ReportResponse = utilities.GetResponse()
          reportResponse.Save(filePath)
        End Using
        Console.WriteLine("Report was downloaded to '{0}'.", filePath)
      Catch e As Exception
        Throw New System.ApplicationException("Failed to download report.", e)
      End Try

    End Sub
  End Class
End Namespace

Get report fields

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201705

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example gets report fields.
  ''' </summary>
  Public Class GetReportFields
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New GetReportFields
      Console.WriteLine(codeExample.Description)
      Try
        Dim reportType As ReportDefinitionReportType = CType( _
            [Enum].Parse(GetType(ReportDefinitionReportType), "INSERT_REPORT_TYPE_HERE"),  _
            ReportDefinitionReportType)
        codeExample.Run(New AdWordsUser, reportType)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example gets report fields."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="reportType">The report type to be run.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal reportType As ReportDefinitionReportType)
      ' Get the ReportDefinitionService.
      Dim reportDefinitionService As ReportDefinitionService = CType(user.GetService( _
          AdWordsService.v201705.ReportDefinitionService), ReportDefinitionService)

      ' The type of the report to get fields for.
      ' E.g.: KEYWORDS_PERFORMANCE_REPORT

      Try
        ' Get the report fields.
        Dim reportDefinitionFields As ReportDefinitionField() = _
            reportDefinitionService.getReportFields(reportType)

        If ((Not reportDefinitionFields Is Nothing) AndAlso _
            (reportDefinitionFields.Length > 0)) Then
          ' Display report fields.
          Console.WriteLine("The report type '{0}' contains the following fields:", reportType)

          For Each reportDefinitionField As ReportDefinitionField In reportDefinitionFields
            Console.Write("- {0} ({1})", reportDefinitionField.fieldName, _
                reportDefinitionField.fieldType)
            If (Not reportDefinitionField.enumValues Is Nothing) Then
              Console.Write(" := [{0}]", String.Join(", ", reportDefinitionField.enumValues))
            End If
            Console.WriteLine()
          Next
        Else
          Console.WriteLine("This report type has no fields.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to retrieve fields for report type.", e)
      End Try
    End Sub
  End Class
End Namespace

Stream criteria report results

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.Util.Reports
Imports Google.Api.Ads.AdWords.v201705
Imports Google.Api.Ads.Common.Util.Reports

Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.IO.Compression
Imports System.Xml

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example streams the results of an ad hoc report, collecting
  ''' total impressions by network from each line. This demonstrates how you
  ''' can extract data from a large report without holding the entire result
  ''' set in memory or using files.
  ''' </summary>
  Public Class StreamCriteriaReportResults
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New StreamCriteriaReportResults
      Console.WriteLine(codeExample.Description)
      Try
        codeExample.Run(New AdWordsUser)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example streams the results of an ad hoc report, collecting" & _
            " total impressions by network from each line. This demonstrates how you" & _
            " can extract data from a large report without holding the entire result" & _
            " set in memory or using files."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    Public Sub Run(ByVal user As AdWordsUser)
      ' Create the query.
      Dim query As String = "SELECT Id, AdNetworkType1, Impressions FROM " & _
          "CRITERIA_PERFORMANCE_REPORT WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS"

      Dim reportUtilities As New ReportUtilities(user, "v201705", query, _
                                     DownloadFormat.GZIPPED_XML.ToString())

      Dim impressionsByAdNetworkType1 As New Dictionary(Of String, Long)

      Try
        Using response As ReportResponse = reportUtilities.GetResponse
          Using gzipStream As GZipStream = New GZipStream(response.Stream, _
              CompressionMode.Decompress)
            Using reader As XmlTextReader = New XmlTextReader(gzipStream)
              While reader.Read
                Select Case reader.NodeType
                  Case XmlNodeType.Element ' The node is an Element.
                    If reader.Name = "row" Then
                      ParseRow(impressionsByAdNetworkType1, reader)
                    End If
                End Select
              End While
            End Using
          End Using
        End Using

        Console.WriteLine("Network, Impressions")
        For Each network As String In impressionsByAdNetworkType1.Keys
          Console.WriteLine("{0}, {1}", network, impressionsByAdNetworkType1(network))
        Next
      Catch e As Exception
        Throw New System.ApplicationException("Failed to download report.", e)
      End Try
    End Sub

    ''' <summary>
    ''' Parses a report row.
    ''' </summary>
    ''' <param name="impressionsByAdNetworkType1">The map that keeps track of
    ''' the impressions grouped by by ad network type1.</param>
    ''' <param name="reader">The XML reader that parses the report.</param>
    Private Sub ParseRow(ByVal impressionsByAdNetworkType1 As Dictionary(Of String, Long), _
        ByVal reader As XmlTextReader)
      Dim network As String = Nothing
      Dim impressions As Long = 0

      While reader.MoveToNextAttribute
        Select Case reader.Name
          Case "network"
            network = reader.Value

          Case "impressions"
            impressions = Long.Parse(reader.Value)
        End Select
      End While

      If Not (network Is Nothing) Then
        If Not (impressionsByAdNetworkType1.ContainsKey(network)) Then
          impressionsByAdNetworkType1(network) = 0
        End If
        impressionsByAdNetworkType1(network) += impressions
      End If
    End Sub
  End Class
End Namespace

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.