Community Discussion

Ask a Question
Back to All

Query each site spent in the last seven days against campaign_id and site

i always get 400.

Here's my code. Please help me improve it. Please

import requests
from datetime import datetime, timedelta

# 全局变量
client_id = 'xxx'
client_secret = 'xxx'
access_token = "xxx"
account_id = "xxx-sc"
campaign_id = "xxx"
base_url = "https://backstage.taboola.com/backstage/api/1.0/"

headers = {
    "Authorization": f"Bearer {access_token}"
}

def get_access_token(client_id, client_secret):
    url = 'https://backstage.taboola.com/backstage/oauth/token'
    payload = {
        'client_id': client_id,
        'client_secret': client_secret,
        'grant_type': 'client_credentials'
    }
    headers = {"content-type": "application/x-www-form-urlencoded"}
    response = requests.post(url, data=payload, headers=headers)
    return response.json()['access_token']
    
def get_campaign_details(account_id, campaign_id):
    url = f"{base_url}{account_id}/campaigns/{campaign_id}/"
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        print("Error fetching campaign details:", response.status_code)
        return None

def get_campaign_summary(account_id, campaign_id, start_date, end_date, site):
    url = f"{base_url}{account_id}/reports/campaign-summary/dimensions/day"
    params = {
        "start_date": start_date,
        "end_date": end_date,
        "campaign": campaign_id,
        "site": site
    }
    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
        return response.json()
    else:
        print("Error fetching campaign summary:", response.status_code)
        return None

def main():
    # access_token = get_access_token(client_id, client_secret)
    # print(access_token)
    campaign_details = get_campaign_details(account_id, campaign_id)
    if campaign_details and 'publisher_targeting' in campaign_details:
        sites = campaign_details['publisher_targeting']
        if sites:
            end_date = datetime.now().date()
            start_date = end_date - timedelta(days=7)

            site_spent = []
            for site in sites:
                summary = get_campaign_summary(account_id, campaign_id, start_date, end_date, site)
                if summary:
                    total_spent = sum(item['spent'] for item in summary['results'])
                    site_spent.append((site, total_spent))

            site_spent.sort(key=lambda x: x[1], reverse=True)
            print("Top 10 sites by spent:")
            for site, spent in site_spent[:10]:
                print(f"Site: {site}, Spent: {spent}")

if __name__ == "__main__":
    main()