The code samples below provide examples of common reporting functions using the AdWords API. Client Library.
Download a criteria performance report with AWQL
' Copyright 2018 Google LLC ' ' 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.v201809 Imports Google.Api.Ads.Common.Util.Reports Imports System.IO Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <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, "v201809", 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
Download a criteria performance report using selectors
' Copyright 2018 Google LLC ' ' 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.v201809 Imports Google.Api.Ads.Common.Util.Reports Imports System.IO Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <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, "v201809", 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
Get the report fields from a report
' Copyright 2018 Google LLC ' ' 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.v201809 Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <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) Using reportDefinitionService As ReportDefinitionService = CType( user.GetService( AdWordsService.v201809.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 Using End Sub End Class End Namespace
Stream results from a report
' Copyright 2018 Google LLC ' ' 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.Util.Reports.v201809 Imports Google.Api.Ads.AdWords.v201809 Imports Google.Api.Ads.Common.Util.Reports Imports System.IO.Compression Imports System.Xml Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <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 ReportQuery = New ReportQueryBuilder() _ .Select("Id", "AdNetworkType1", "Impressions") _ .From(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT) _ .Where("Status").In("ENABLED", "PAUSED") _ .During(ReportDefinitionDateRangeType.LAST_7_DAYS) _ .Build() Dim reportUtilities As New ReportUtilities(user, "v201809", 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
Stream results from a report as objects
' Copyright 2018 Google LLC ' ' 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.Util.Reports.v201809 Imports Google.Api.Ads.AdWords.v201809 Imports Google.Api.Ads.Common.Util.Reports Imports System.IO.Compression Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <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 StreamCriteriaReportToPoco 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 StreamCriteriaReportToPoco 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 ReportQuery = New ReportQueryBuilder() _ .Select("Id", "AdNetworkType1", "Impressions") _ .From(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT) _ .Where("Status").In("ENABLED", "PAUSED") _ .During(ReportDefinitionDateRangeType.LAST_7_DAYS) _ .Build() Dim reportUtilities As New ReportUtilities(user, "v201809", 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) ' Deserialize the report into a list of CriteriaReportRow. ' You can also deserialize the list into your own POCOs as follows. ' 1. Annotate your class properties with ReportRow annotation. ' ' Public Class MyCriteriaReportRow ' ' <ReportColumn> ' Public Property KeywordID as Long ' ' <ReportColumn> ' Public Property Impressions as Long ' End Class ' ' 2. Deserialize into your own report rows. ' ' Dim report As New AwReport(Of CriteriaReportRow) _ ' (New AwXmlTextReader(gzipStream), "Example") Using report As New AwReport(Of CriteriaReportRow) _ (New AwXmlTextReader(gzipStream), "Example") While report.MoveNext() Console.WriteLine(report.Current.Impressions) Console.Write(" ") Console.Write(report.Current.KeywordId) 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 End Class Public Class CriteriaReportRow Private _KeywordId As Long Private _Impressions As Long <ReportColumn("keywordID")> Public Property KeywordId As Long Get Return _KeywordId End Get Set(value As Long) _KeywordId = value End Set End Property <ReportColumn("impressions")> Public Property Impressions As Long Get Return _Impressions End Get Set(value As Long) _Impressions = value End Set End Property End Class End Namespace
Stream results from a report as objects of a predefined report row type
' Copyright 2018 Google LLC ' ' 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.Util.Reports.v201809 Imports Google.Api.Ads.AdWords.v201809 Imports Google.Api.Ads.Common.Util.Reports Imports System.IO.Compression Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <summary> ''' This code example streams the results of an ad hoc report, and ''' returns the data in the report as objects of a predefined report row type. ''' </summary> Public Class StreamReportToPredefinedReportRowType 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 StreamReportToPredefinedReportRowType 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, and " & "returns the data in the report as objects of a predefined report row type." 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 AccountCurrencyCode, AccountDescriptiveName" & " FROM FINAL_URL_REPORT DURING LAST_7_DAYS" Dim reportUtilities As New ReportUtilities(user, "v201809", 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 report As New AwReport(Of FinalUrlReportReportRow) _ (New AwXmlTextReader(gzipStream), "Example") While report.MoveNext() Console.WriteLine(report.Current.accountCurrencyCode) Console.Write(" ") Console.Write(report.Current.accountDescriptiveName) 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 End Class End Namespace