You can assign a budget to a campaign, dissociate a budget from a campaign, or
retrieve the campaigns that are assigned to a specific budget.

## Assign a budget to a campaign

After you have
[created a `CampaignBudget`](https://developers.google.com/google-ads/api/docs/campaigns/budgets/create-budgets.md.txt)
with [`CampaignBudgetService`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignBudgetService.md.txt)
or [identified an existing one](https://developers.google.com/google-ads/api/docs/campaigns/budgets/share-budgets.md.txt),
use its [`resource_name`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignBudget.md.txt#resource_name)
field value in a call to [`CampaignService`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignService.md.txt). If
the budget creation operation succeeds in a separate request, but the subsequent
campaign assignment fails, you will have an orphaned budget (a budget that is
not associated with any campaign). You can avoid orphaned budgets by creating
both the `CampaignBudget` (using a temporary resource ID) and the `Campaign`
atomically in a single [`GoogleAdsService.Mutate`](https://developers.google.com/google-ads/api/reference/rpc/v26/GoogleAdsService/Mutate.md.txt) request,
or by reusing or [removing](https://developers.google.com/google-ads/api/docs/campaigns/budgets/remove-budgets.md.txt) unused
budgets.

### New campaign

For a new campaign, in the
[`CampaignOperation.create`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignOperation.md.txt#create),
set the [`campaign_budget`](https://developers.google.com/google-ads/api/reference/rpc/v26/Campaign.md.txt#campaign_budget)
field of the [`Campaign`](https://developers.google.com/google-ads/api/reference/rpc/v26/Campaign.md.txt) object to a budget resource
name, as demonstrated in the following code example:


### Java

```java
// Creates the campaign.
Campaign campaign =
    Campaign.newBuilder()
        .setName("Interplanetary Cruise #" + getPrintableDateTime())
        .setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
        // Recommendation: Set the campaign to PAUSED when creating it to prevent
        // the ads from immediately serving. Set to ENABLED once you've added
        // targeting and the ads are ready to serve
        .setStatus(CampaignStatus.PAUSED)
        // Sets the bidding strategy and budget.
        .setManualCpc(ManualCpc.newBuilder().build())
        .setCampaignBudget(budgetResourceName)
        // Adds the networkSettings configured above.
        .setNetworkSettings(networkSettings)
        // Declares whether this campaign serves political ads targeting the EU.
        .setContainsEuPoliticalAdvertising(DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING)
        // Optional: Sets the start & end dates.
        .setStartDateTime(new DateTime().plusDays(1).toString("yyyy-MM-dd 00:00:00"))
        .setEndDateTime(new DateTime().plusDays(30).toString("yyyy-MM-dd 23:59:59"))
        .build();
      
```

### C#

```c#
// Create the campaign.
Campaign campaign = new Campaign()
{
    Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
    AdvertisingChannelType = AdvertisingChannelType.Search,

    // Recommendation: Set the campaign to PAUSED when creating it to prevent
    // the ads from immediately serving. Set to ENABLED once you've added
    // targeting and the ads are ready to serve
    Status = CampaignStatus.Paused,

    // Set the bidding strategy and budget.
    ManualCpc = new ManualCpc(),
    CampaignBudget = budget,

    // Set the campaign network options.
    NetworkSettings = new NetworkSettings
    {
        TargetGoogleSearch = true,
        TargetSearchNetwork = true,
        // Enable Display Expansion on Search campaigns. See
        // https://support.google.com/google-ads/answer/7193800 to learn more.
        TargetContentNetwork = true,
        TargetPartnerSearchNetwork = false
    },

    // Declare whether or not this campaign contains political ads targeting the EU.
    ContainsEuPoliticalAdvertising = EuPoliticalAdvertisingStatus.DoesNotContainEuPoliticalAdvertising,

    // Optional: Set the start date.
    StartDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd 00:00:00"),

    // Optional: Set the end date.
    EndDateTime = DateTime.Now.AddYears(1).ToString("yyyyMMdd 23:59:59"),
};
      
```

### PHP

```php
$campaign = new Campaign([
    'name' => 'Interplanetary Cruise #' . Helper::getPrintableDatetime(),
    'advertising_channel_type' => AdvertisingChannelType::SEARCH,
    // Recommendation: Set the campaign to PAUSED when creating it to prevent
    // the ads from immediately serving. Set to ENABLED once you've added
    // targeting and the ads are ready to serve.
    'status' => CampaignStatus::PAUSED,
    // Sets the bidding strategy and budget.
    'manual_cpc' => new ManualCpc(),
    'campaign_budget' => $budgetResourceName,
    // Adds the network settings configured above.
    'network_settings' => $networkSettings,
    // Declare whether or not this campaign serves political ads targeting the EU.
    'contains_eu_political_advertising' =>
        EuPoliticalAdvertisingStatus::DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING,
    // Optional: Sets the start and end dates.
    'start_date_time' => date('Y-m-d 00:00:00', strtotime('+1 day')),
    'end_date_time' => date('Y-m-d 23:59:59', strtotime('+1 month'))
]);
      
```

### Python

```python
# Create campaign.
campaign_operation: CampaignOperation = client.get_type("CampaignOperation")
campaign: Campaign = campaign_operation.create
campaign.name = f"Interplanetary Cruise {uuid.uuid4()}"
campaign.advertising_channel_type = (
    client.enums.AdvertisingChannelTypeEnum.SEARCH
)

# Recommendation: Set the campaign to PAUSED when creating it to prevent
# the ads from immediately serving. Set to ENABLED once you've added
# targeting and the ads are ready to serve.
campaign.status = client.enums.CampaignStatusEnum.PAUSED

# Set the bidding strategy and budget.
campaign.manual_cpc = client.get_type("ManualCpc")
campaign.campaign_budget = campaign_budget_response.results[0].resource_name

# Set the campaign network options.
campaign.network_settings.target_google_search = True
campaign.network_settings.target_search_network = True
campaign.network_settings.target_partner_search_network = False
# Enable Display Expansion on Search campaigns. For more details see:
# https://support.google.com/google-ads/answer/7193800
campaign.network_settings.target_content_network = True

# Declare whether or not this campaign serves political ads targeting the
# EU. Valid values are:
#   CONTAINS_EU_POLITICAL_ADVERTISING
#   DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING
campaign.contains_eu_political_advertising = (
    client.enums.EuPoliticalAdvertisingStatusEnum.DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING
)

# Optional: Set the start date.
start_time: datetime.date = datetime.date.today() + datetime.timedelta(
    days=1
)
campaign.start_date_time = datetime.date.strftime(
    start_time, _START_DATE_FORMAT
)

# Optional: Set the end date.
end_time: datetime.date = start_time + datetime.timedelta(weeks=4)
campaign.end_date_time = datetime.date.strftime(end_time, _END_DATE_FORMAT)
      
```

### Ruby

```ruby
# Create campaign.
campaign = client.resource.campaign do |c|
  c.name = "Interplanetary Cruise #{(Time.new.to_f * 1000).to_i}"
  c.advertising_channel_type = :SEARCH

  # Recommendation: Set the campaign to PAUSED when creating it to prevent
  # the ads from immediately serving. Set to ENABLED once you've added
  # targeting and the ads are ready to serve.
  c.status = :PAUSED

  # Set the bidding strategy and budget.
  c.manual_cpc = client.resource.manual_cpc
  c.campaign_budget = return_budget.results.first.resource_name

  # Set the campaign network options.
  c.network_settings = client.resource.network_settings do |ns|
    ns.target_google_search = true
    ns.target_search_network = true
    # Enable Display Expansion on Search campaigns. See
    # https://support.google.com/google-ads/answer/7193800 to learn more.
    ns.target_content_network = true
    ns.target_partner_search_network = false
  end

  # Declare whether or not this campaign serves political ads targeting the EU.
  # Valid values are CONTAINS_EU_POLITICAL_ADVERTISING and
  # DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING.
  c.contains_eu_political_advertising = :DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING

  # Optional: Set the start date.
  c.start_date_time = DateTime.parse((Date.today + 1).to_s).strftime('%Y%m%d %H:%M:%S')

  # Optional: Set the end date.
  c.end_date_time = DateTime.parse((Date.today.next_year).to_s).strftime('%Y%m%d %H:%M:%S')
end
      
```

### Perl

```perl
# Create a campaign.
my $campaign = Google::Ads::GoogleAds::V26::Resources::Campaign->new({
    name                   => "Interplanetary Cruise #" . uniqid(),
    advertisingChannelType => SEARCH,
    # Recommendation: Set the campaign to PAUSED when creating it to stop
    # the ads from immediately serving. Set to ENABLED once you've added
    # targeting and the ads are ready to serve.
    status => PAUSED,
    # Set the bidding strategy and budget.
    manualCpc      => Google::Ads::GoogleAds::V26::Common::ManualCpc->new(),
    campaignBudget => $campaign_budgets_response->{results}[0]{resourceName},
    # Set the campaign network options.
    networkSettings =>
      Google::Ads::GoogleAds::V26::Resources::NetworkSettings->new({
        targetGoogleSearch  => "true",
        targetSearchNetwork => "true",
        # Enable Display Expansion on Search campaigns. See
        # https://support.google.com/google-ads/answer/7193800 to learn more.
        targetContentNetwork       => "true",
        targetPartnerSearchNetwork => "false"
      }
      ),
    # Declare whether or not this campaign serves political ads targeting the EU.
    # Valid values are CONTAINS_EU_POLITICAL_ADVERTISING and
    # DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING.
    containsEuPoliticalAdvertising =>
      DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING,
    # Optional: Set the start datetime. The campaign starts tomorrow.
    startDateTime =>
      strftime("%Y%m%d 00:00:00", localtime(time + 60 * 60 * 24)),
    # Optional: Set the end datetime. The campaign runs for 30 days.
    endDateTime =>
      strftime("%Y%m%d 23:59:59", localtime(time + 60 * 60 * 24 * 30)),
  });
      
```

### curl

> [!NOTE]
> **Note:** While a direct REST code sample for this step isn't provided here, you can achieve this using a manual REST request.   
>
> Refer to the Google Ads API REST interface documentation and the method-specific reference pages. You will need to construct the JSON payload based on the proto definitions.   
>
> Key Resources:
>
> - [Using REST](https://developers.google.com/google-ads/api/rest/overview.md.txt)
> - [REST Interface Structure](https://developers.google.com/google-ads/api/rest/design/overview.md.txt)
> - [JSON Field Mappings](https://developers.google.com/google-ads/api/rest/design/json-mappings.md.txt)
> - Consult the [REST API Reference](https://developers.google.com/google-ads/api/reference/rpc/latest/overview) for the specific service and method.

<br />

### Existing campaign

To replace the budget of an existing campaign, in a
[`CampaignOperation.update`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignOperation.md.txt#update),
set the [`campaign_budget`](https://developers.google.com/google-ads/api/reference/rpc/v26/Campaign.md.txt#campaign_budget) field
of the [`Campaign`](https://developers.google.com/google-ads/api/reference/rpc/v26/Campaign.md.txt) object to
the resource name of an existing budget (along with any other campaign
fields that you might want to set). This replaces the existing
budget assigned to the campaign with the one specified by the `campaign_budget`
field, since a campaign can be associated with only one budget at a time.

> [!WARNING]
> **Warning:** The best practice is to update your existing budget rather than replacing it with a newly created budget. All the spend accumulated on an existing campaign budget is ignored if you assign a new campaign budget to an existing campaign. Also, modifying a daily budget within 30 days can lead to [overdelivery](https://support.google.com/google-ads/answer/2393018). For example, if you have a budget set for $10, spend that $10, and then assign a new budget for $11 on the same day, your campaign could spend around $21. If you instead update the existing budget's amount to $11, your daily spend target remains $11.

## Dissociate a budget from a campaign

A campaign must always be associated with a budget. You can remove a budget
from a campaign by changing the budget associated with the campaign, thereby
[replacing it with another budget](https://developers.google.com/google-ads/api/docs/campaigns/budgets/assign-budgets.md.txt#existing-campaign). To identify campaigns
using a particular budget, see the next section.

## Retrieve campaigns assigned to a budget

Obtaining the list of campaigns that use the same budget can be helpful in
balancing budget utilization. The following GAQL query returns
all campaigns for the specified budget ID:

```sql
SELECT campaign.id
FROM campaign
WHERE campaign_budget.id = campaign_budget_id
```