How to request Campaign PErformance Report using Python from Bing Ads API?

32 Views Asked by At

I was trying to request data from Bing Ads using this code:

import requests

# Replace these variables with your own data
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
tenant_id = 'YOUR_TENANT_ID'
account_id = 'YOUR_ACCOUNT_ID'
customer_id = 'YOUR_CUSTOMER_ID'
refresh_token = 'YOUR_REFRESH_TOKEN'  # Obtain this through the OAuth flow

# Get access token
def get_access_token(client_id, client_secret, tenant_id, refresh_token):
    token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/token'
    data = {
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token,
        'client_id': client_id,
        'client_secret': client_secret,
        'resource': 'https://ads.microsoft.com'
    }
    response = requests.post(token_url, data=data)
    response.raise_for_status()
    return response.json()['access_token']

# Call the API to retrieve data
def get_campaign_data(access_token, account_id, customer_id):
    api_url = f'https://api.ads.microsoft.com/Reporting/v13/CampaignPerformanceReportRequest'
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json',
        'DeveloperToken': 'YOUR_DEVELOPER_TOKEN',  # Obtain this from your Bing Ads account
        'CustomerId': customer_id,
        'AccountId': account_id
    }
    # Define your report request here (refer to the API documentation for the correct format)
    report_request = {}
    response = requests.post(api_url, headers=headers, json=report_request)
    response.raise_for_status()
    return response.content

# Example usage
try:
    access_token = get_access_token(client_id, client_secret, tenant_id, refresh_token)
    campaign_data = get_campaign_data(access_token, account_id, customer_id)
    print(campaign_data)
except requests.HTTPError as e:
    print(f'An HTTP error occurred: {e.response.status_code}')

But for some reason I only get errors 401, any idea what is wrong? For my tenant_id, I'm using "common" and for customer_id/account_id, I'm using clid, and aid from Bing Ads campaign page (params from url). Refresh token was generated like a 5 days ago so should still be valid. Developer token was from developer Bing ads with super admin generated.

Export data from Bing Ads with Python code to get detailed view (CampaignPerformanceReportRequest)

0

There are 0 best solutions below