Bing Ads Python SDK

13.0.27 · active · verified Sun Apr 12

The Bing Ads Python SDK (pypi-slug: `bingads`) is a client library designed to simplify interactions with the Microsoft Advertising (formerly Bing Ads) SOAP API. It provides proxy classes for various web services, abstracts OAuth authentication, and offers high-level interfaces for campaign management, bulk operations, and reporting. The library is actively maintained with frequent updates to reflect changes in Bing Ads API Version 13.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with the Bing Ads API using OAuth and retrieve a list of accessible accounts. It assumes you have a Developer Token, Client ID, and a pre-obtained Refresh Token (which for server-side applications requires an initial interactive OAuth consent flow to acquire). Ensure `BINGADS_DEVELOPER_TOKEN`, `BINGADS_CLIENT_ID`, and `BINGADS_REFRESH_TOKEN` environment variables are set or replace the placeholders directly.

import os
from bingads.authorization import AuthorizationData, OAuthDesktopMobileApplication
from bingads.service_client import ServiceClient

# --- Configuration (replace with your actual values or env vars) ---
DEVELOPER_TOKEN = os.environ.get('BINGADS_DEVELOPER_TOKEN', 'YOUR_DEVELOPER_TOKEN_HERE')
CLIENT_ID = os.environ.get('BINGADS_CLIENT_ID', 'YOUR_CLIENT_ID_HERE')
REFRESH_TOKEN = os.environ.get('BINGADS_REFRESH_TOKEN', '') # Obtain this initially via user consent flow

# NOTE: For server-side apps, the REFRESH_TOKEN needs to be obtained once via a browser-based flow
# and then stored securely. This example assumes a refresh token is available.

# Define the OAuth scope for the Bing Ads API.
OAUTH_SCOPE = ['https://ads.microsoft.com/.default']

if not REFRESH_TOKEN:
    print("WARNING: REFRESH_TOKEN not set. This example will only work if you manually obtain a refresh token.")
    print("Refer to Bing Ads Python SDK documentation for obtaining refresh token via OAuth flow.")
    # In a real application, you'd initiate the OAuth flow here if no refresh token is present.
    # For this quickstart, we'll proceed assuming an empty token or one from env.

# Setup AuthorizationData
authorization_data = AuthorizationData(
    developer_token=DEVELOPER_TOKEN,
    authentication=OAuthDesktopMobileApplication(
        client_id=CLIENT_ID,
        oauth_scopes=OAUTH_SCOPE
    )
)

# Set the refresh token if available
if REFRESH_TOKEN:
    authorization_data.authentication.refresh_token = REFRESH_TOKEN

# Example: Get a list of accessible accounts
try:
    # Get Customer Management Service Client
    customer_service = ServiceClient(
        service='CustomerManagementService',
        version=13,
        authorization_data=authorization_data
    )

    # Authenticate and get an access token (if refresh token is valid)
    if not authorization_data.authentication.oauth_tokens:
        authorization_data.authentication.request_oauth_tokens(authorization_data.authentication.refresh_token)
    
    # If the refresh token was empty, this will likely fail unless the user interactively provides consent.
    # For a quickstart, we assume refresh_token is pre-populated for non-interactive execution.
    print(f"Access Token: {authorization_data.authentication.oauth_tokens.access_token[:10]}...\n")

    # Get User accounts
    user_accounts = customer_service.GetAccountsInfo(
        UserId=None, # None implies current authenticated user
        ReturnAdditionalFields=customer_service.factory.create('AccountAdditionalField').None
    )

    if user_accounts and user_accounts.AccountInfo:
        print("Successfully retrieved accounts:")
        for account in user_accounts.AccountInfo:
            print(f"- Account ID: {account.Id}, Name: {account.Name}, Number: {account.Number}")
    else:
        print("No accounts found or accessible.")

except Exception as e:
    print(f"An error occurred: {e}")
    if "AuthenticationToken" in str(e) or "DeveloperToken" in str(e) or "Customer " in str(e):
        print("Please ensure your DEVELOPER_TOKEN, CLIENT_ID, and REFRESH_TOKEN are correctly configured and valid.")
        print("If running for the first time or if the refresh token is expired, you might need to run an interactive OAuth flow.")

view raw JSON →