Introducing the Bing Ads Python SDK


We are excited to announce the availability of the Bing Ads Python SDK Beta today. This SDK client library will improve your Bing Ads developer experience by providing high-level access to features such as:

This post is an overview of the main features available within the Bing Ads Python SDK. You can find more details about these and other features on our MSDN page. Our Bing Ads Python SDK is distributed through pypi and the open source code can be downloaded from github.

Bulk API

Since its first announcement, the Bulk API has offered an efficient way to manage your campaigns, keywords and other entities, transferring large amounts of data up to ten times faster than traditional SOAP APIs. However, as a text-based API, the Bulk API requires a lot of work on the client side to parse and process the files containing the Bing Ads entities. On the other hand, traditional SOAP APIs can be easily accessed using an automatically generated object model.

The Bing Ads SDK closes this gap by providing an infrastructure for accessing the Bulk API using the same object model as our SOAP APIs.

Our SDK makes it very easy now to migrate your existing code working with the SOAP API objects to take advantage of the Bulk API. For example, one of the most popular requests from advertisers is the ability to quickly update keyword bids under their account based on their performance. Here’s how it can be done using the Bing Ads SDK:

First we instantiate a BulkServiceManager object:

bulk_service=BulkServiceManager(
    authorization_data=authorization_data
)

Then download the keywords including their performance data during the last month:

performance_stats_date_range=bulk_service.factory.create('PerformanceStatsDateRange')
performance_stats_date_range.PredefinedTime='LastMonth'
download_parameters=DownloadParameters(
    data_scope=[ 'EntityData' , 'EntityPerformanceData' ],
    entities=[ 'Keywords' ],
    performance_stats_date_range=performance_stats_date_range
)

bulk_entities=bulk_service.download_entities(download_parameters)

And finally upload the keywords back, while increasing the bids by 10 for the keywords that had received more than 100 clicks:

keywords=[]
for entity in bulk_entities:
    if isinstance(entity, BulkKeyword) \
    and hasattr(entity.performance_data, 'clicks') \
    and entity.performance_data.clicks > 100:
        entity.keyword.Bid.Amount=entity.keyword.Bid.Amount * 1.10
        keywords.append(entity)

if keywords.count > 0:
    entity_upload_parameters=EntityUploadParameters(
        entities=keywords
    )

    bulk_entities=bulk_service.upload_entities(entity_upload_parameters)

    # output the uploaad results
    for entity in bulk_entities:
        if isinstance(entity, BulkKeyword):
            output_bulk_keywords([entity])

The SDK also provides an easy way to write your objects to the bulk files or parse existing bulk files. Please check out the MSDN documentation for the BulkFileReader and BulkFileWriter.

OAuth Authorization

As you may already know, Bing Ads is now actively transitioning to the OAuth Authorization model, a better and more secure way to handle user authentication than the traditional username/password authentication. To make this transition easier for our customers, the Bing Ads SDK includes high-level implementations of standard OAuth 2.0 grant flows, including the authorization code grant flow for both web and desktop applications and the implicit grant flow for desktop applications.

For example, to start using the OAuth authorization code grant flow, you have to first instantiate the corresponding OAuth object. If you are building a web app:

oauth_web_auth_code_grant = OAuthWebAuthCodeGrant(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    redirection_uri=REDIRECTION_URI
)

Or if you are working on a desktop app:

oauth_desktop_mobile_auth_code_grant = OAuthDesktopMobileAuthCodeGrant(
    client_id=CLIENT_ID
)

Then you can get the url to direct the user to the Microsoft Account authorization page:

oauth_web_auth_code_grant.get_authorization_endpoint()

And once you are called back by the Microsoft Account authorization server, you can request the OAuth tokens by using the received authorization response uri:

oauth_web_auth_code_grant.request_oauth_tokens_by_response_uri(RESPONSE_URI)
oauth_tokens = oauth_web_auth_code_grant.oauth_tokens
access_token = oauth_tokens.access_token

When using the OAuth objects with the ServiceClient class (described in the next section), your access and refresh tokens will be automatically refreshed upon the access token expiration. Optionally you can register a callback function to automatically save the refresh token anytime it is refreshed. For example if you defined have a save_refresh_token() method that securely stores your refresh token, set the

authentication token_refreshed_callback property.
oauth_web_auth_code_grant.token_refreshed_callback=save_refresh_token

Please check our Getting Started Guide on MSDN for complete examples of using the OAuth classes in a web or desktop application.

SOAP APIs

One of our goals in the Bing Ads SDK is to make sure it’s easy to access the SOAP APIs without doing any additional work. We have included a wrapper ServiceClient class that provides uniform access to all of our SOAP services. It also handles common request header fields for you, allowing to specify the values for fields such as CustomerId, AccountId, DeveloperToken etc. in the AuthorizationData object only once.

Here is an example of initializing the AuthorizationData object using the OAuthWebAuthCodeGrant instance defined above: 

authorization_data=AuthorizationData(
    developer_token=DEVELOPER_TOKEN,
    authentication=oauth_web_auth_code_grant,
    # IDs not required for Customer Management service
    account_id=AccountIdGoesHere,
    customer_id=CustomerIdGoesHere,
)

The Authentication property can hold one of the OAuth Authorization objects (for authorization code grant flow or implicit grant flow also described in the previous section) or the PasswordAuthentication object (if you want to use the user name/password authentication).

password_authentication=PasswordAuthentication(
    user_name='UserNameGoesHere',
    password='PasswordGoesHere'
)
authorization_data=AuthorizationData(
    developer_token=DEVELOPER_TOKEN,
    authentication= password_authentication
)

Now that we have the AuthorizationData object, we can create the ServiceClient and call API operations without passing the same information with every request:

customer_service=ServiceClient(
    'CustomerManagementService',
    authorization_data=authorization_data
)

# Set to an empty user identifier to get the current authenticated Bing Ads user
user_id=None
user=customer_service.GetUser(user_id).User

Note that we only set the UserId field on the GetUserRequest. All other fields will be taken from the AuthorizationData object that we provided earlier.

Whenever the current access token expires, ServiceClient and BulkServiceManager will request a new set of access and refresh tokens from the Microsoft Account authorization server on your behalf. To ensure you always have the latest refresh token, you should listen for new tokens received by registering a callback function. For example if you have a save_refresh_token that stores a refresh token securely, register it with the token_refreshed_callback authentication property.

authorization_data.authentication.token_refreshed_callback=save_refresh_token

Please check our Getting Started Guide on MSDN for complete examples of using the ServiceClient with the AuthorizationData and OAuth classes in your web or desktop  application.

Additional Resources

Please check our MSDN pages for more information about working with the Bing Ads SDK:

Coming soon

Our Java SDK will be out of beta and released for general availability later this week.

Feedback

Please let us know what you think about the Bing Ads SDK by sending an email to bing_ads_sdk@microsoft.com or leaving a comment below. We want to know about your experience coding with the Bing Ads SDK and what we can do to help you minimize your coding time and maximize conversions. 

Comments (0)

Skip to main content