Skip to main content
Python code example
Updated over a week ago

This is an example of Python code to get started with the API. It runs a simple report, then polls the status endpoint until the report is done. When the report is done, it displays the URL to download the report.


import requests
import time
import os

# User input
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"]
}"""

# User input using environment variable
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.")

# Constants
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, data=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
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"])
else:
if i >= retry_count:
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}")

Did this answer your question?