# Получить активные кампании
curl -X GET "https://api.targetads.io/v1/meta/campaigns?project_id=12486&active=true" \
-H "Authorization: Bearer YOUR_TOKEN"
# Получить все кампании
curl -X GET "https://api.targetads.io/v1/meta/campaigns?project_id=12486&active=false" \
-H "Authorization: Bearer YOUR_TOKEN" {
"campaigns": [
{
"placement_id": 12345,
"placement_name": "Campaign Name 1",
"placement_created": "2024-01-15 10:30:00",
"placement_status": "active",
"source_id": 1,
"source_name": "Google Ads",
"marketing_campaign_id": 678,
"marketing_name": "Marketing Campaign 1"
},
{
"placement_id": 12346,
"placement_name": "Campaign Name 2",
"placement_created": "2024-02-01 14:20:00",
"placement_status": "active",
"source_id": 2,
"source_name": "Facebook Ads",
"marketing_campaign_id": 679,
"marketing_name": "Marketing Campaign 2"
}
],
"count": 2
} {
"campaigns": [],
"count": 0
} GET /v1/meta/token_validate?project_id={project_id} curl -X GET "https://api.targetads.io/v1/meta/token_validate?project_id=12345" \
-H "Authorization: Bearer YOUR_TOKEN" {
"valid": true,
"project_id": 12345,
"is_admin": false,
"campaign_access": [12345, 12346, 12347],
"expires_at": "2025-12-31T23:59:59Z"
} {
"ErrorCode": 401,
"ErrorMessage": "invalid or expired token"
}
GET /v1/meta/target_event?project_id={project_id}
curl -X GET "https://api.targetads.io/v1/meta/target_event?project_id=12345" \
-H "Authorization: Bearer YOUR_TOKEN"
{
"target_events": [
{
"event_type": "ecommerce",
"event_category": "transaction",
"event_name": "Purchase",
"description": "Покупка товара"
},
{
"event_type": "lead",
"event_category": "form",
"event_name": "ContactForm",
"description": "Отправка формы обратной связи"
},
{
"event_type": "engagement",
"event_category": "video",
"event_name": "VideoComplete",
"description": "Полный просмотр видео"
}
],
"count": 3
}
import requests
API_URL = "https://api.targetads.io"
PROJECT_ID = 12345
HEADERS = {
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json"
}
def get_campaigns(project_id, active=True):
"""Получить список доступных кампаний"""
response = requests.get(
f"{API_URL}/v1/meta/campaigns",
params={
"project_id": project_id,
"active": active
},
headers=HEADERS
)
response.raise_for_status()
return response.json()['campaigns']
def get_raw_data_by_campaigns(project_id, date_from, date_to):
"""Получить raw data, разделяя по кампаниям"""
campaigns = get_campaigns(project_id, active=True)
all_data = []
# Разбиваем по 10 кампаний
for i in range(0, len(campaigns), 10):
batch = campaigns[i:i+10]
campaign_ids = [c['placement_id'] for c in batch]
payload = {
"ResponseType": "JSON",
"Fields": ["InteractionTime", "InteractionType", "InteractionUrlPath"],
"InteractionFilter": {
"DateFrom": date_from,
"DateTo": date_to,
"InteractionType": ["PageView"],
"MediaCampaignId": campaign_ids
}
}
response = requests.post(
f"{API_URL}/v1/reports/raw_reports",
params={"project_id": project_id},
json=payload,
headers=HEADERS
)
response.raise_for_status()
all_data.extend(response.json()['data'])
return all_data
def validate_token_before_start(project_id):
"""Валидация токена и получение информации о доступе"""
try:
response = requests.get(
f"{API_URL}/v1/meta/token_validate",
params={"project_id": project_id},
headers=HEADERS
)
response.raise_for_status()
token_info = response.json()
if not token_info['valid']:
raise Exception("Token is invalid")
print(f"Token valid until: {token_info['expires_at']}")
print(f"Admin access: {token_info['is_admin']}")
if not token_info['is_admin']:
print(f"Access to {len(token_info['campaign_access'])} campaigns")
return token_info
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
raise Exception("Token is invalid or expired")
raise
def get_target_events(project_id):
"""Получить список целевых событий"""
response = requests.get(
f"{API_URL}/v1/meta/target_event",
params={"project_id": project_id},
headers=HEADERS
)
response.raise_for_status()
return response.json()['target_events']
def build_target_filter(project_id, event_names):
"""Построить фильтр по названиям событий"""
all_events = get_target_events(project_id)
# Проверить что события существуют
available_names = {e['event_name'] for e in all_events}
for name in event_names:
if name not in available_names:
print(f"Warning: event {name} not found in project")
return {
"EventName": [name for name in event_names if name in available_names]
} from datetime import datetime, timedelta
import json
class MetaCache:
def __init__(self, project_id, headers):
self.project_id = project_id
self.headers = headers
self.cache = {}
self.cache_duration = timedelta(hours=1)
def get_campaigns(self, active=True, force_refresh=False):
"""Получить кампании с кэшированием"""
cache_key = f"campaigns_active_{active}"
if not force_refresh and cache_key in self.cache:
cached_data, cached_time = self.cache[cache_key]
if datetime.now() - cached_time < self.cache_duration:
return cached_data
# Запросить свежие данные
response = requests.get(
f"{API_URL}/v1/meta/campaigns",
params={"project_id": self.project_id, "active": active},
headers=self.headers
)
response.raise_for_status()
campaigns = response.json()['campaigns']
self.cache[cache_key] = (campaigns, datetime.now())
return campaigns
def get_campaign_name(self, placement_id):
"""Получить название кампании по ID"""
campaigns = self.get_campaigns(active=False)
campaign = next((c for c in campaigns if c['placement_id'] == placement_id), None)
return campaign['placement_name'] if campaign else f"Campaign {placement_id}"
def process_large_report(project_id, date_from, date_to):
"""Обработка больших отчетов с разделением по кампаниям"""
# 1. Получить список активных кампаний
campaigns = get_campaigns(project_id, active=True)
print(f"Found {len(campaigns)} active campaigns")
# 2. Обработать каждую кампанию
results = []
for campaign in campaigns:
print(f"Processing campaign: {campaign['placement_name']}")
try:
data = get_raw_data(
project_id=project_id,
campaign_ids=[campaign['placement_id']],
date_from=date_from,
date_to=date_to
)
results.extend(data)
except Exception as e:
print(f"Error processing campaign {campaign['placement_id']}: {e}")
continue
return results
def monitor_api_access(project_id):
"""Мониторинг состояния токена и доступа"""
# Валидация токена
token_info = validate_token(project_id)
# Проверка срока действия
expires_at = datetime.fromisoformat(token_info['expires_at'].replace('Z', '+00:00'))
days_until_expiry = (expires_at - datetime.now()).days
if days_until_expiry < 30:
print(f"WARNING: Token expires in {days_until_expiry} days")
# Проверка доступа к кампаниям
campaigns = get_campaigns(project_id)
print(f"Access to {len(campaigns)} campaigns")
# Проверка целевых событий
events = get_target_events(project_id)
print(f"Project has {len(events)} target events configured")
return {
"token_expires_in_days": days_until_expiry,
"campaigns_count": len(campaigns),
"events_count": len(events)
} def build_reference_data(project_id):
"""Построение справочников для отчетов"""
campaigns = get_campaigns(project_id, active=False)
events = get_target_events(project_id)
# Справочник кампаний
campaign_dict = {
c['placement_id']: {
'name': c['placement_name'],
'source': c['source_name'],
'marketing_campaign': c['marketing_name']
}
for c in campaigns
}
# Справочник событий
event_dict = {
e['event_name']: {
'type': e['event_type'],
'category': e['event_category'],
'description': e['description']
}
for e in events
}
return {
'campaigns': campaign_dict,
'events': event_dict
}
{
"ErrorCode": 400,
"ErrorMessage": "invalid project_id"
}
{
"ErrorCode": 401,
"ErrorMessage": "invalid or expired token"
}
{
"ErrorCode": 403,
"ErrorMessage": "access denied to project"
}
{
"ErrorCode": 500,
"ErrorMessage": "internal error"
} Лимиты и ограничения
API имеет технические ограничения, которые следует
учитывать при построении интеграции: