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

namespace Microsoft\BingAds\Samples\V13;

// For more information about installing and using the Bing Ads PHP SDK, 
// see https://go.microsoft.com/fwlink/?linkid=838593.

require_once __DIR__ . "/../vendor/autoload.php";

include __DIR__ . "/AuthHelper.php";
include __DIR__ . "/AdInsightExampleHelper.php";
include __DIR__ . "/CampaignManagementExampleHelper.php";

use SoapVar;
use SoapFault;
use Exception;

// Specify the Microsoft\BingAds\Auth classes that will be used.
use Microsoft\BingAds\Auth\ServiceClient;
use Microsoft\BingAds\Auth\ServiceClientType;

// Specify the Microsoft\BingAds\Samples classes that will be used.
use Microsoft\BingAds\Samples\V13\AuthHelper;
use Microsoft\BingAds\Samples\V13\AdInsightExampleHelper;
use Microsoft\BingAds\Samples\V13\CampaignManagementExampleHelper;

try
{
    // Authenticate user credentials and set the account ID for the sample.  
    AuthHelper::Authenticate();

    print("-----\r\nGetCampaignsByAccountId:\r\n");
    $getCampaignsByAccountIdResponse = CampaignManagementExampleHelper::GetCampaignsByAccountId(
        $GLOBALS['AuthorizationData']->AccountId,
        AuthHelper::CampaignTypes,
        AuthHelper::CampaignAdditionalFields
    );
    $campaigns = $getCampaignsByAccountIdResponse->Campaigns;
    print("Campaigns:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfCampaign($campaigns);

    // Get the budget opportunities for each campaign in the current account.
    
    if(count((array)$campaigns) == 0 || !isset($campaigns->Campaign))
    {
        return;
    }

    foreach ($campaigns->Campaign as $campaign)
    {
        print("-----\r\nGetBudgetOpportunities:\r\n");
        $opportunities = AdInsightExampleHelper::GetBudgetOpportunities(
            $campaign->Id
        )->Opportunities;
        AdInsightExampleHelper::OutputArrayOfBudgetOpportunity($opportunities);
    }
}
catch (SoapFault $e)
{
    printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
    var_dump($e->detail);
    print "-----\r\nLast SOAP request/response:\r\n";
    print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
    // Ignore fault exceptions that we already caught.
    if ($e->getPrevious())
    { ; }
    else
    {
        print $e->getCode()." ".$e->getMessage()."\n\n";
        print $e->getTraceAsString()."\n\n";
    }
}
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