Edit

Budget Opportunities Code Example

This example demonstrates how to get the budget opportunities for each campaign in the current authenticated account.

Tip

Use the language selector in the documentation header to choose C#, Java, Php, or Python.

To get access and refresh tokens for your Microsoft Advertising user and make your first service call using the Bing Ads API, see the Quick Start guide. You'll want to review the Get Started guide and walkthroughs for your preferred language e.g., C#, Java, Php, and Python.

Supporting files for C#, Java, Php, and Python examples are available at GitHub. You can clone each repository or repurpose snippets as needed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.AdInsight;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How to get the budget opportunities for each campaign in the current authenticated account.
    /// </summary>
    public class BudgetOpportunities : ExampleBase
    {
        public override string Description
        {
            get { return "Budget Opportunities | AdInsight V13"; }
        }

        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

                AdInsightExampleHelper AdInsightExampleHelper = new AdInsightExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                AdInsightExampleHelper.AdInsightService = new ServiceClient<IAdInsightService>(
                    authorizationData: authorizationData,
                    environment: environment);

                CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                    authorizationData: authorizationData,
                    environment: environment);

                OutputStatusMessage("-----\nGetCampaignsByAccountId:");
                var campaigns = (await CampaignManagementExampleHelper.GetCampaignsByAccountIdAsync(
                    accountId: authorizationData.AccountId,
                    campaignType: AllCampaignTypes,
                    returnAdditionalFields: CampaignAdditionalField.AdScheduleUseSearcherTimeZone)).Campaigns;
                OutputStatusMessage("Campaigns:");
                CampaignManagementExampleHelper.OutputArrayOfCampaign(campaigns);

                IList<BudgetOpportunity> opportunities = null;

                // Get the budget opportunities for each campaign in the current account.

                foreach (var campaign in campaigns)
                {
                    if (campaign.Id != null)
                    {
                        OutputStatusMessage("-----\nGetBudgetOpportunities:");
                        opportunities = (await AdInsightExampleHelper.GetBudgetOpportunitiesAsync(
                            campaignId: (long)campaign.Id)).Opportunities;
                        OutputStatusMessage("Opportunities:");
                        AdInsightExampleHelper.OutputArrayOfBudgetOpportunity(opportunities);
                    }
                }
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch AdInsight service exceptions
            catch (FaultException<Microsoft.BingAds.V13.AdInsight.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.V13.AdInsight.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
    }
}
package com.microsoft.bingads.examples.v13;

import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
import com.microsoft.bingads.v13.adinsight.*;

import java.util.ArrayList;

public class BudgetOpportunities extends ExampleBase {

    static ServiceClient<IAdInsightService> AdInsightService;
    static ServiceClient<ICampaignManagementService> CampaignService;
    
    public static void main(java.lang.String[] args) {
     
        try
        {
            authorizationData = getAuthorizationData();
             
            AdInsightExampleHelper.AdInsightService = new ServiceClient<IAdInsightService>(
                    authorizationData, 
                    API_ENVIRONMENT,
                    IAdInsightService.class);
            
            CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                    authorizationData, 
                    API_ENVIRONMENT,
                    ICampaignManagementService.class);
             
            // Get the budget opportunities for each campaign in the current account.

            ArrayList<CampaignType> campaignTypes = new ArrayList<CampaignType>();
            campaignTypes.add(CampaignType.AUDIENCE);
            campaignTypes.add(CampaignType.SHOPPING);
            campaignTypes.add(CampaignType.SEARCH);
                                    
            outputStatusMessage("-----\nGetCampaignsByAccountId:");
            GetCampaignsByAccountIdResponse getCampaignsByAccountIdResponse = CampaignManagementExampleHelper.getCampaignsByAccountId(
                authorizationData.getAccountId(),
                campaignTypes,
                null
            );
            ArrayOfCampaign campaigns = getCampaignsByAccountIdResponse.getCampaigns();
            outputStatusMessage("Campaigns:");
            CampaignManagementExampleHelper.outputArrayOfCampaign(campaigns);  
            
            ArrayOfBudgetOpportunity opportunities = null;
            
            for (Campaign campaign : campaigns.getCampaigns())
            {
                if (campaign.getId() != null)
                {
                    outputStatusMessage("-----\nGetBudgetOpportunities:");
                    opportunities = AdInsightExampleHelper.getBudgetOpportunities(
                            (long)campaign.getId()).getOpportunities();
                    outputStatusMessage("Opportunities:");
                    AdInsightExampleHelper.outputArrayOfBudgetOpportunity(opportunities);
                }
            }        
        } 
        catch (Exception ex) {
            String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
            outputStatusMessage(faultXml);
            String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
            outputStatusMessage(message);
        }
    }
}
<?php

use Microsoft\MsAds\Rest\ApiException;
use Microsoft\MsAds\Rest\Model\AdInsightService\GetBudgetOpportunitiesRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\GetCampaignsByAccountIdRequest;
use Microsoft\MsAds\Rest\Test\RestApiTestBase;

class BudgetOpportunitiesTest extends RestApiTestBase
{
    /**
     * @throws ApiException
     */
    public function testGetBudgetOpportunitiesForAllCampaigns()
    {
        // Get all campaigns for the account
        $request = new GetCampaignsByAccountIdRequest([
            'AccountId' => self::CUSTOMER_ACCOUNT_ID
        ]);
        $campaignsResponse = self::$campaignManagementServiceApi->getCampaignsByAccountId($request);
        $campaigns = $campaignsResponse->getCampaigns();
        $this->assertIsArray($campaigns);
        if (empty($campaigns)) {
            $this->markTestSkipped('No campaigns found for the account.');
        }
        foreach ($campaigns as $campaign) {
            $request = new GetBudgetOpportunitiesRequest([
                'CampaignId' => $campaign->getId()
            ]);
            $response = self::$adInsightServiceApi->getBudgetOpportunities($request);
            $opportunities = $response->getOpportunities();
            print_r($opportunities);
        }
    }
}

from auth_helper import *
from openapi_client.models.adinsight import *
from openapi_client.models.campaign import *


def main(authorization_data):
    try:
        # Get all campaigns for the account
        get_campaigns_request = GetCampaignsByAccountIdRequest(
            account_id=authorization_data.account_id
        )
        
        campaigns_response = campaign_service.get_campaigns_by_account_id(
            get_campaigns_by_account_id_request=get_campaigns_request
        )
        
        campaigns = campaigns_response.Campaigns
        
        if not campaigns or len(campaigns) == 0:
            print("No campaigns found for the account.")
            return
        
        print(f"Found {len(campaigns)} campaigns. Getting budget opportunities...")
        
        # Get budget opportunities for each campaign
        for campaign in campaigns:
            if campaign.Id:
                try:
                    get_budget_opportunities_request = GetBudgetOpportunitiesRequest(
                        campaign_id=campaign.Id
                    )
                    
                    response = ad_insight_service.get_budget_opportunities(
                        get_budget_opportunities_request=get_budget_opportunities_request
                    )
                    
                    opportunities = response.Opportunities
                    
                    if opportunities and len(opportunities) > 0:
                        print(f"\nCampaign ID: {campaign.Id}, Name: {campaign.Name}")
                        print(f"Budget Opportunities: {len(opportunities)}")
                        for opportunity in opportunities:
                            print(f"  - Opportunity: {opportunity}")
                    else:
                        print(f"\nCampaign ID: {campaign.Id}, Name: {campaign.Name}")
                        print("  No budget opportunities found.")
                        
                except Exception as ex:
                    print(f"Error getting budget opportunities for campaign {campaign.Id}: {str(ex)}")
                    
    except Exception as ex:
        print(f"Error occurred: {str(ex)}")


if __name__ == '__main__':
    print("Loading the web service client...")
    
    authorization_data = AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )
    
    authenticate(authorization_data)
    
    campaign_service = ServiceClient(
        service='CampaignManagementService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT,
    )
    
    ad_insight_service = ServiceClient(
        service='AdInsightService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT,
    )
    
    main(authorization_data)

See Also

Get Started with the Bing Ads API