Zmień sprawdzone metody

Zadbaj o dobrą organizację dzięki kolekcji Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.

Tymczasowe nazwy zasobów

GoogleAdsService.Mutate obsługuje tymczasowe nazwy zasobów, do których można później odwoływać się w tym samym żądaniu. Dzięki temu możesz na przykład utworzyć kampanię i powiązane z nią grupy reklam, reklamy, słowa kluczowe itd. w jednym żądaniu.

Możesz to zrobić, określając resource_name nowego zasobu w celu zastosowania negatywnego identyfikatora. Jeśli na przykład utworzysz kampanię i określisz jej nazwę zasobu jako customers/<YOUR_CUSTOMER_ID>/campaigns/-1, to podczas tworzenia grupy reklam w trakcie późniejszej operacji możesz odwoływać się do niej za pomocą tej nazwy zasobu, a podany -1 zostanie automatycznie zastąpiony rzeczywistym identyfikatorem utworzonej kampanii.

Podczas korzystania z tymczasowych nazw zasobów pamiętaj o tych kwestiach:

  • Tymczasowej nazwy zasobu można użyć dopiero po zdefiniowaniu jej w zasobie. W poniższym przykładzie operacja grupy reklam pojawi się po operacji kampanii na liście operacji.
  • Tymczasowe nazwy zasobów nie są zapamiętywane w zadaniach ani żądaniach mutacji. Aby odwołać się do zasobu utworzonego w poprzednim zadaniu lub do mutacji, użyj jego rzeczywistej nazwy zasobu.
  • W przypadku pojedynczego zadania lub żądania mutacji każda tymczasowa nazwa zasobu musi mieć niepowtarzalną ujemną liczbę, nawet jeśli pochodzą one z różnych typów zasobów. Jeśli tymczasowy identyfikator zostanie ponownie użyty w pojedynczym zadaniu lub żądaniu mutacji, zostanie zwrócony błąd.

Przykład

Aby podać bardziej konkretny przykład sytuacji opisanej powyżej, załóżmy, że chcesz dodać kampanię, grupę reklam i reklamę w jednym żądaniu do interfejsu API. Utwórz strukturę żądania analogiczną do tej:

mutate_operations: [
  {
    campaign_operation: {
      create: {
        resource_name: "customers/<YOUR_CUSTOMER_ID>/campaigns/-1",
        ...
      }
    }
  },
  {
    ad_group_operation: {
      create: {
        resource_name: "customers/<YOUR_CUSTOMER_ID>/adGroups/-2",
        campaign: "customers/<YOUR_CUSTOMER_ID>/campaigns/-1"
        ...
      }
    }
  },
  {
    ad_group_ad_operation: {
      create: {
        ad_group: "customers/<YOUR_CUSTOMER_ID>/adGroups/-2"
        ...
      }
    }
  },
]

Zwróć uwagę, że w tej grupie reklam używany jest nowy identyfikator tymczasowy, ponieważ nie możemy ponownie użyć -1 w tej kampanii. Poza tym odwołujemy się do tej grupy reklam podczas tworzenia reklamy w grupie reklam. Sama grupa reklam odwołuje się do nazwy zasobu określonej przez nas w ramach wcześniejszej operacji żądania, a element resource_name w elemencie ad_group_ad_operation nie jest potrzebny, ponieważ nie odwołuje się do niego żadna inna operacja.

Operacje grup tego samego typu

Ważne jest, aby przy korzystaniu z GoogleAdsService.Mutate grupować operacje według ich zasobu w tablicy powtarzanych operacji. Ogólnie ta metoda mutacji umożliwia automatyczne sekwencyjne wywoływanie poszczególnych metod mutacji poszczególnych zasobów. W tym celu odczytuje dane dotyczące operacji, dopóki nie znajdzie 1 zasobu dla innego typu zasobów, a następnie grupuje wszystkie operacje tego samego typu w jednym żądaniu.

Jeśli na przykład masz 5 operacji kampanii, a następnie 10 operacji grup reklam w powtórzonym polu operations w wywołaniu Mutate, system przeprowadzi 2 całkowite wywołania w backendzie – jedno do CampaignService dla 5 operacji, a następne obok AdGroupService w przypadku 10 operacji. Jeśli jednak pogrupujesz je inaczej, skuteczność może być znacznie gorzej. Jeśli utworzysz tylko 2 kampanie i 2 grupy reklam, ale ustawisz je tak, aby działania miały kolejność [campaign, ad group, campaign, ad group], zostaną zsumowane 4 wywołania w backendzie. Może to spowolnić działanie interfejsu API i w skrajnych przypadkach nawet spowodować przekroczenie limitu czasu.

Pobieranie zmiennych atrybutów z odpowiedzi

Jeśli response_content_type żądania mutacji zmienisz na MUTABLE_RESOURCE, odpowiedź będzie zawierać wartości wszystkich pól zmodyfikowanych dla każdego obiektu utworzonego lub zaktualizowanego w żądaniu. Użyj tej funkcji, aby uniknąć dodatkowych żądań search lub searchStream po każdym żądaniu mutacji.

Jeśli nie ustawisz response_content_type, interfejs Google Ads API otrzyma domyślną wartość RESOURCE_NAME_ONLY, a odpowiedź będzie zawierać tylko nazwy zasobów każdego utworzonego lub zaktualizowanego zasobu.

Oto przykład pobrania zmodyfikowanego zasobu z wywołania interfejsu API:

Java

// Constructs a request to add the bid modifier.
MutateCampaignBidModifiersRequest request =
    MutateCampaignBidModifiersRequest.newBuilder()
        .addOperations(op)
        .setCustomerId(String.valueOf(customerId))
        // Specifies that we want to the request to return the mutated object and not just its
        // resource name.
        .setResponseContentType(ResponseContentType.MUTABLE_RESOURCE)
        .build();

// Sends the operation in a mutate request.
try (CampaignBidModifierServiceClient agcServiceClient =
    googleAdsClient.getLatestVersion().createCampaignBidModifierServiceClient()) {
  MutateCampaignBidModifiersResponse response =
      agcServiceClient.mutateCampaignBidModifiers(request);
  /**
   * The resource returned in the response can be accessed directly in the results list. Its
   * fields can be read directly, and it can also be mutated further and used in subsequent
   * requests, without needing to make additional Get or Search requests.
   */
  CampaignBidModifier mutableResource = response.getResults(0).getCampaignBidModifier();
  System.out.printf(
      "Created campaign bid modifier with resource_name "
          + "'%s', criterion ID "
          + "%d, and bid modifier value "
          + "%s, under the campaign with "
          + "resource_name '%s'.%n",
      mutableResource.getResourceName(),
      mutableResource.getCriterionId(),
      mutableResource.getBidModifier(),
      mutableResource.getCampaign());
}
      

C#

// Construct an operation to create the campaign bid modifier.
CampaignBidModifierOperation op = new CampaignBidModifierOperation()
{
    Create = campaignBidModifier
};

// Construct a request, and set the ResponseContentType field to
// ResponseContentType.MutableResource, so that the response contains
// the mutated object and not just its resource name.
MutateCampaignBidModifiersRequest request = new MutateCampaignBidModifiersRequest()
{
    CustomerId = customerId.ToString(),
    ResponseContentType = ResponseContentType.MutableResource,
    Operations = { op }
};

// Send the operation in a mutate request.
try
{
    MutateCampaignBidModifiersResponse response =
        campaignBidModifierService.MutateCampaignBidModifiers(request);
    Console.WriteLine("Added {0} campaign bid modifiers:", response.Results.Count);

    // The resource returned in the response can be accessed directly in the
    // results list. Its fields can be read directly, and it can also be mutated
    // further and used in subsequent requests, without needing to make
    // additional Get or Search requests.
    foreach (MutateCampaignBidModifierResult result in response.Results)
    {
        Console.WriteLine($"\tCreated campaign bid modifier with " +
            $"resource name '{result.ResourceName}', " +
            $"criterion ID '{result.CampaignBidModifier.CriterionId}', " +
            $"and bid modifier value {result.CampaignBidModifier.BidModifier}, " +
            $"under the campaign with resource_name " +
            $"'{result.CampaignBidModifier.Campaign}'");
    }
}
catch (GoogleAdsException e)
{
    Console.WriteLine("Failure:");
    Console.WriteLine($"Message: {e.Message}");
    Console.WriteLine($"Failure: {e.Failure}");
    Console.WriteLine($"Request ID: {e.RequestId}");
    throw;
}
      

PHP

// Issues a mutate request to add the campaign bid modifier.
// Here we pass the optional parameter ResponseContentType::MUTABLE_RESOURCE so that the
// response contains the mutated object and not just its resource name.
$campaignBidModifierServiceClient = $googleAdsClient->getCampaignBidModifierServiceClient();
$response = $campaignBidModifierServiceClient->mutateCampaignBidModifiers(
    $customerId,
    [$campaignBidModifierOperation],
    ['responseContentType' => ResponseContentType::MUTABLE_RESOURCE]
);

// The resource returned in the response can be accessed directly in the results list.
// Its fields can be read directly, and it can also be mutated further and used in
// subsequent requests, without needing to make additional Get or Search requests.
/** @var CampaignBidModifier $addedCampaignBidModifier */
$addedCampaignBidModifier = $response->getResults()[0]->getCampaignBidModifier();
printf(
    "Added campaign bid modifier with resource_name '%s', criterion ID %d, and "
    . "bid modifier value %f, under the campaign with resource name '%s'.%s",
    $addedCampaignBidModifier->getResourceName(),
    $addedCampaignBidModifier->getCriterionId(),
    $addedCampaignBidModifier->getBidModifier(),
    $addedCampaignBidModifier->getCampaign(),
    PHP_EOL
);
      

Python

# Add the campaign bid modifier. Here we pass the optional parameter
# response_content_type=MUTABLE_RESOURCE so that the response contains
# the mutated object and not just its resource name.
request = client.get_type("MutateCampaignBidModifiersRequest")
request.customer_id = customer_id
request.operations = [campaign_bid_modifier_operation]
request.response_content_type = (
    client.enums.ResponseContentTypeEnum.MUTABLE_RESOURCE
)

campaign_bm_response = campaign_bm_service.mutate_campaign_bid_modifiers(
    request=request
)

# The resource returned in the response can be accessed directly in the
# results list. Its fields can be read directly, and it can also be mutated
# further and used in subsequent requests, without needing to make
# additional Get or Search requests.
mutable_resource = campaign_bm_response.results[0].campaign_bid_modifier
print(
    "Created campaign bid modifier with resource_name "
    f"'{mutable_resource.resource_name}', criterion ID "
    f"'{mutable_resource.criterion_id}', and bid modifier value "
    f"'{mutable_resource.bid_modifier}', under the campaign with "
    f"resource_name '{mutable_resource.campaign}', "
)
      

Ruby

# Add the campaign bid modifier. Here we pass the optional parameter
# response_content_type=MUTABLE_RESOURCE so that the response contains
# the mutated object and not just its resource name.
response = campaign_bid_modifier_service.mutate_campaign_bid_modifiers(
  customer_id: customer_id,
  operations: [operation],
  response_content_type: :MUTABLE_RESOURCE,
)

puts "Added #{response.results.size} campaign bid modifiers:"
response.results.each do |added_campaign_bid_modifier|
  # The resource returned in the response can be accessed directly in the
  # results list. Its fields can be read directly, and it can also be mutated
  # further and used in subsequent requests, without needing to make
  # additional Get or Search requests.
  mutable_resource = added_campaign_bid_modifier.campaign_bid_modifier
  puts "\tCreated campaign bid modifier with " \
    "resource_name '#{mutable_resource.resource_name}', " \
    "criterion ID #{mutable_resource.criterion_id}, " \
    "bid_modifier #{mutable_resource.bid_modifier}, " \
    "under the campaign with resource_name '#{mutable_resource.campaign}'"
end
      

Perl

# Add the campaign bid modifier. Here we pass the optional parameter
# responseContentType => MUTABLE_RESOURCE so that the response contains the
# mutated object and not just its resource name.
my $campaign_bid_modifiers_response =
  $api_client->CampaignBidModifierService()->mutate({
    customerId          => $customer_id,
    operations          => [$campaign_bid_modifier_operation],
    responseContentType => MUTABLE_RESOURCE
  });

# The resource returned in the response can be accessed directly in the
# results list. Its fields can be read directly, and it can also be mutated
# further and used in subsequent requests, without needing to make additional
# Get or Search requests.
my $mutable_resource =
  $campaign_bid_modifiers_response->{results}[0]{campaignBidModifier};

printf
  "Created campaign bid modifier with resource name '%s', criterion ID %d, "
  . "and bid modifier value %s, under the campaign with resource name '%s'.\n",
  $mutable_resource->{resourceName}, $mutable_resource->{criterionId},
  $mutable_resource->{bidModifier},  $mutable_resource->{campaign};