Skip to content
TAM Reporting

Examples

Official Python example for TAM Reporting.

This is the TAM Help Center Python example: run a one-time report, poll status every 10 seconds, and print the download URL. It times out after 6 hours. Read the API key from TAM_API_KEY — never commit a key.

import os
import time

import requests

payload = {
    "format": "csv",
    "filters": {
        "date": {
            "start": "2023-02-08T00:00:00.000",
            "end": "2023-02-08T23:59:59.000",
            "timezone": "UTC",
        }
    },
    "dimensions": ["day", "advertiser_name"],
    "metrics": ["impression"],
}

TAM_API_KEY = os.getenv("TAM_API_KEY")
if TAM_API_KEY is None:
    raise EnvironmentError(
        "TAM_API_KEY environment variable is required but not set."
    )

TAM_API_BASE_URL = "https://ads.teads.tv/"
TAM_API_RUN_ONETIME_REPORT_ENDPOINT = TAM_API_BASE_URL + "api/reports/run"
TAM_API_REPORT_STATUS_ENDPOINT = TAM_API_BASE_URL + "api/reports/status"
TIMEOUT_HOUR = 6
STATUS_FETCH_INTERVAL_SECOND = 10

headers = {
    "Authorization": TAM_API_KEY,
    "Content-Type": "application/json",
    "Accept": "application/json",
}

try:
    run_report_response = requests.request(
        "POST",
        TAM_API_RUN_ONETIME_REPORT_ENDPOINT,
        headers=headers,
        json=payload,
    )
    run_report_response.raise_for_status()
    report_id = run_report_response.json()["id"]

    if report_id:
        print("Report request successful. Report id:", report_id)
        retry_count = TIMEOUT_HOUR * 60 * 60 // STATUS_FETCH_INTERVAL_SECOND
        status = None
        status_response = None
        for i in range(retry_count):
            status_response = requests.request(
                "GET",
                TAM_API_REPORT_STATUS_ENDPOINT + "/" + report_id,
                headers=headers,
            ).json()
            status = status_response["status"]
            if status not in ["queued", "processing"]:
                break
            print("Report is", status)
            time.sleep(STATUS_FETCH_INTERVAL_SECOND)

        if status == "finished":
            print("Report can be downloaded here:", status_response["uri"])
        elif i >= retry_count - 1:
            print("Timeout waiting for report to finish")
        else:
            print("Report failed, status is", status)
except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
    print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
    print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
    print(f"An error occurred: {req_err}")

Change the filters.date range, dimensions, and metrics to match your report. Use dimension and metric API names.