Share your feedback about the Google Ads (AdWords) API. Take the 2021 AdWords API and Google Ads API Annual Survey.

The AdWords API will sunset on April 27, 2022. Migrate to the Google Ads API to take advantage of the latest Google Ads features.

Targeting Samples

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

Add targeting criteria to a campaign

' 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 adds various types of targeting criteria to a campaign.
    ''' To get a list of campaigns, run GetCampaigns.vb.
    ''' </summary>
    Public Class AddCampaignTargetingCriteria
        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 AddCampaignTargetingCriteria
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
                Dim feedIdText As String = "INSERT_LOCATION_FEED_ID_HERE"

                Dim feedId As Long? = Nothing
                Dim temp As Long = 0

                If Long.TryParse(feedIdText, temp) Then
                    feedId = temp
                End If

                codeExample.Run(New AdWordsUser(), campaignId, feedId)
            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 adds various types of targeting criteria to a campaign. " &
                    "To get a list of campaigns, run GetCampaigns.vb."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId">Id of the campaign to which targeting criteria
        ''' are added.</param>
        ''' <param name="feedId">ID of a feed that has been configured for location
        ''' targeting, meaning it has an ENABLED FeedMapping with criterionType of
        ''' 77. Feeds linked to a GMB account automatically have this FeedMapping.
        ''' If you don't have such a feed, set this value to Nothing.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long, ByVal feedId As Long?)
            Using campaignCriterionService As CampaignCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignCriterionService),
                CampaignCriterionService)

                ' Create locations. The IDs can be found in the documentation or
                ' retrieved with the LocationCriterionService.
                Dim california As New Location
                california.id = 21137L

                Dim mexico As New Location
                mexico.id = 2484L

                ' Create languages. The IDs can be found in the documentation or
                ' retrieved with the ConstantDataService.
                Dim english As New Language
                english.id = 1000L

                Dim spanish As New Language
                spanish.id = 1003L

                Dim criteria As New List(Of Criterion)()
                criteria.AddRange(New Criterion() { _
                                                      california, mexico, english, spanish
                                                  })

                ' Distance targeting. Area of 10 miles around the locations in the location feed.
                If feedId.HasValue Then
                    Dim radiusLocationGroup As New LocationGroups
                    radiusLocationGroup.feedId = feedId.Value

                    Dim radiusMatchingFunction As New [Function]
                    radiusMatchingFunction.operator = FunctionOperator.IDENTITY

                    Dim radiusOperand As New LocationExtensionOperand
                    radiusOperand.radius = New ConstantOperand
                    radiusOperand.radius.type = ConstantOperandConstantType.DOUBLE
                    radiusOperand.radius.unit = ConstantOperandUnit.MILES
                    radiusOperand.radius.doubleValue = 10

                    radiusMatchingFunction.lhsOperand = New FunctionArgumentOperand() _
                        {radiusOperand}

                    criteria.Add(radiusLocationGroup)
                End If

                ' Create operations to add each of the criteria above.
                Dim operations As New List(Of CampaignCriterionOperation)

                For Each criterion As Criterion In criteria
                    Dim campaignCriterion As New CampaignCriterion
                    campaignCriterion.campaignId = campaignId
                    campaignCriterion.criterion = criterion

                    Dim operation As New CampaignCriterionOperation
                    operation.operator = [Operator].ADD
                    operation.operand = campaignCriterion

                    operations.Add(operation)
                Next

                ' Add a negative campaign criterion.

                Dim negativeCriterion As New NegativeCampaignCriterion
                negativeCriterion.campaignId = campaignId

                Dim keyword As New Keyword
                keyword.text = "jupiter cruise"
                keyword.matchType = KeywordMatchType.BROAD

                negativeCriterion.criterion = keyword

                Dim negativeCriterionOperation As New CampaignCriterionOperation
                negativeCriterionOperation.operand = negativeCriterion
                negativeCriterionOperation.operator = [Operator].ADD

                operations.Add(negativeCriterionOperation)

                Try
                    ' Set the campaign targets.
                    Dim retVal As CampaignCriterionReturnValue = campaignCriterionService.mutate(
                        operations.ToArray())

                    ' Display the results.
                    If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing)) Then
                        For Each criterion As CampaignCriterion In retVal.value
                            Console.WriteLine(
                                "Campaign criterion of type '{0}' was set to campaign with id " &
                                "= '{1}'.", criterion.criterion.CriterionType, criterion.campaignId)
                        Next
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to set campaign criteria.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Add negative criteria to a customer

' 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 adds various types of negative criteria to a customer. These criteria
    ''' will be applied to all campaigns for the customer.
    ''' </summary>
    Public Class AddCustomerNegativeCriteria
        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 AddCustomerNegativeCriteria
            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 adds various types of negative criteria to a customer. " +
                       "These criteria will be applied to all campaigns for the customer."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        Public Sub Run(ByVal user As AdWordsUser)
            Using customerNegativeCriterionService As CustomerNegativeCriterionService =
                CType(user.GetService(AdWordsService.v201809.CustomerNegativeCriterionService),
                      CustomerNegativeCriterionService)

                Dim criteria As New List(Of Criterion)

                ' Exclude tragedy & conflict content.
                Dim tragedyContentLabel As New ContentLabel()
                tragedyContentLabel.contentLabelType = ContentLabelType.TRAGEDY
                criteria.Add(tragedyContentLabel)

                ' Exclude a specific placement.
                Dim placement As New Placement()
                placement.url = "http://www.example.com"
                criteria.Add(placement)

                ' Additional criteria types are available for this service. See the types listed
                ' under Criterion here:
                ' https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion

                ' Create operations to add each of the criteria above.
                Dim operations As New List(Of CustomerNegativeCriterionOperation)
                For Each criterion As Criterion In criteria
                    Dim negativeCriterion As New CustomerNegativeCriterion()
                    negativeCriterion.criterion = criterion
                    Dim operation As New CustomerNegativeCriterionOperation()
                    operation.operator = [Operator].ADD
                    operation.operand = negativeCriterion
                    operations.Add(operation)
                Next

                Try
                    ' Send the request to add the criteria.
                    Dim result As CustomerNegativeCriterionReturnValue =
                            customerNegativeCriterionService.mutate(operations.ToArray())

                    ' Display the results.
                    For Each negativeCriterion As CustomerNegativeCriterion In result.value
                        Console.WriteLine(
                            "Customer negative criterion with criterion ID {0} and type '{1}' " +
                            "was added.", negativeCriterion.criterion.id,
                            negativeCriterion.criterion.type)
                    Next
                Catch e As Exception
                    Throw _
                        New System.ApplicationException("Failed to set customer negative criteria.",
                                                        e)
                End Try

            End Using
        End Sub
    End Class
End Namespace

Get all campaign criteria

' 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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example gets all targeting criteria for a campaign.  To set
    ''' campaign targeting criteria, run AddCampaignTargetingCriteria.vb. To get
    ''' campaigns, run GetCampaigns.vb.
    ''' </summary>
    Public Class GetCampaignTargetingCriteria
        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 GetCampaignTargetingCriteria
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
                codeExample.Run(New AdWordsUser, campaignId)
            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 all targeting criteria for a campaign.  To set " &
                    "campaign targeting criteria, run AddCampaignTargetingCriteria.vb. To get " &
                    "campaigns, run GetCampaigns.vb."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId">Id of the campaign from which targeting
        ''' criteria are retrieved.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
            Using campaignCriterionService As CampaignCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignCriterionService),
                CampaignCriterionService)

                ' Create the selector.
                Dim selector As New Selector
                selector.fields = New String() { _
                                                   Criterion.Fields.Id,
                                                   Criterion.Fields.CriteriaType,
                                                   CampaignCriterion.Fields.CampaignId
                                               }

                ' Set the filters.
                Dim predicate As New Predicate
                predicate.field = "CampaignId"
                predicate.operator = PredicateOperator.EQUALS
                predicate.values = New String() {campaignId.ToString}

                selector.predicates = New Predicate() {predicate}

                ' Set the selector paging.
                selector.paging = Paging.Default
                Dim page As New CampaignCriterionPage

                Try
                    Dim i As Integer = 0
                    Do
                        ' Get all campaign targets.
                        page = campaignCriterionService.get(selector)

                        ' Display the results.
                        If ((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) Then
                            For Each campaignCriterion As CampaignCriterion In page.entries
                                Dim negative As String = ""
                                If (TypeOf campaignCriterion Is NegativeCampaignCriterion) Then
                                    negative = "Negative "
                                End If
                                Console.WriteLine(
                                    "{0}) {1}Campaign targeting criterion with id = '{2}' and " &
                                    "Type = {3} was found for campaign id '{4}'", i, negative,
                                    campaignCriterion.criterion.id,
                                    campaignCriterion.criterion.type,
                                    campaignCriterion.campaignId)
                                i += 1
                            Next
                        End If
                        selector.paging.IncreaseOffset()
                    Loop While (selector.paging.startIndex < page.totalNumEntries)
                    Console.WriteLine("Number of campaign targeting criteria found: {0}",
                                      page.totalNumEntries)
                Catch e As Exception
                    Throw New _
                        System.ApplicationException("Failed to get campaign targeting criteria.",
                                                    e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Get all targetable languages and carriers

' 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 illustrates how to retrieve all carriers and languages
    ''' available for targeting.
    ''' </summary>
    Public Class GetTargetableLanguagesAndCarriers
        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 GetTargetableLanguagesAndCarriers
            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 illustrates how to retrieve all carriers and languages" &
                       "available for targeting."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        Public Sub Run(ByVal user As AdWordsUser)
            Using constantDataService As ConstantDataService = CType(
                user.GetService(
                    AdWordsService.v201809.ConstantDataService),
                ConstantDataService)

                Try
                    ' Get all carriers.
                    Dim carriers As Carrier() = constantDataService.getCarrierCriterion

                    ' Display the results.
                    If (Not carriers Is Nothing) Then
                        For Each carrier As Carrier In carriers
                            Console.WriteLine(
                                "Carrier name is '{0}', ID is {1} and country code is '{2}'.",
                                carrier.name, carrier.id, carrier.countryCode)
                        Next
                    Else
                        Console.WriteLine("No carriers were retrieved.")
                    End If

                    ' Get all languages.
                    Dim languages As Language() = constantDataService.getLanguageCriterion

                    ' Display the results.
                    If (Not languages Is Nothing) Then
                        For Each language As Language In languages
                            Console.WriteLine("Language name is '{0}', ID is {1} and code " &
                                              "is '{2}'.", language.name, language.id,
                                              language.code)
                        Next
                    Else
                        Console.WriteLine("No languages were found.")
                    End If
                Catch e As Exception
                    Throw _
                        New System.ApplicationException(
                            "Failed to get targetable carriers and languages.",
                            e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Get location criteria by name

' 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 location criteria by name.
    ''' </summary>
    Public Class LookupLocation
        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 LookupLocation
            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 gets location criteria by name."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        Public Sub Run(ByVal user As AdWordsUser)
            Using locationCriterionService As LocationCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.LocationCriterionService),
                LocationCriterionService)

                Dim locationNames As String() = New String() _
                        {"Paris", "Quebec", "Spain", "Deutschland"}

                Dim selector As New Selector
                selector.fields = New String() { _
                                                   Location.Fields.Id, Location.Fields.LocationName,
                                                   LocationCriterion.Fields.CanonicalName,
                                                   Location.Fields.DisplayType,
                                                   Location.Fields.ParentLocations,
                                                   LocationCriterion.Fields.Reach,
                                                   Location.Fields.TargetingStatus
                                               }

                selector.predicates = New Predicate() { _
                                                          Predicate.In(Location.Fields.LocationName,
                                                                       locationNames),
                                                          Predicate.Equals(
                                                              LocationCriterion.Fields.Locale, "en")
                                                      }

                Try
                    ' Make the get request.
                    Dim locationCriteria As LocationCriterion() =
                            locationCriterionService.get(selector)

                    ' Display the resulting location criteria.
                    For Each locationCriterion As LocationCriterion In locationCriteria
                        Dim parentLocations As String = "N/A"

                        If ((Not locationCriterion.location Is Nothing) AndAlso
                            (Not locationCriterion.location.parentLocations Is Nothing)) Then
                            Dim parentLocationList As New List(Of String)
                            For Each location As Location In _
                                locationCriterion.location.parentLocations
                                parentLocationList.Add(GetLocationString(location))
                            Next
                            parentLocations = String.Join(", ", parentLocationList)
                        End If

                        Console.WriteLine(
                            "The search term '{0}' returned the location '{1}' of type '{2}' " &
                            "with parent locations '{3}',  reach '{4}' and targeting status '{5}.",
                            locationCriterion.searchTerm, locationCriterion.location.locationName,
                            locationCriterion.location.displayType, parentLocations,
                            locationCriterion.reach,
                            locationCriterion.location.targetingStatus)
                    Next
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to get location criteria.", e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' Gets a string representation for a location.
        ''' </summary>
        ''' <param name="location">The location</param>
        ''' <returns></returns>
        Public Function GetLocationString(ByVal location As Location) As String
            Return String.Format("{0} ({1})", location.locationName, location.displayType)
        End Function
    End Class
End Namespace