Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions examples/get_ad_analytics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""
Example calls to fetch ad analytics data using the adAnalytics finder.

The 3-legged member access token should include the 'r_ads_reporting' scope, which is part of the
Advertising APIs product.

For full documentation on the adAnalytics API, see:
https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/ads-reporting
"""

import os, sys

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())

from linkedin_api.clients.restli.client import RestliClient
import json

ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
if ACCESS_TOKEN is None:
raise Exception(
'A valid access token must be defined in the /examples/.env file under the variable name "ACCESS_TOKEN"'
)

AD_ANALYTICS_RESOURCE = "/adAnalytics"
API_VERSION = "202404"

restli_client = RestliClient()
restli_client.session.hooks["response"].append(lambda r: r.raise_for_status())


"""
Get analytics for a specific ad account, broken down by campaign.

Required query parameters:
- dateRange: Start and end dates for the report
- timeGranularity: DAILY, MONTHLY, or ALL
- pivot: The entity type to group results by (e.g. CAMPAIGN, CREATIVE, ACCOUNT)
- One of: accounts, campaigns, creatives, or campaignGroups (as a list of URNs)

Note: Query parameter values should be passed as native Python types (lists, dicts).
The client handles Rest.li protocol encoding automatically.
"""
response = restli_client.finder(
resource_path=AD_ANALYTICS_RESOURCE,
finder_name="statistics",
query_params={
"pivot": "CAMPAIGN",
"dateRange": {
"start": {"day": 1, "month": 1, "year": 2024},
"end": {"day": 31, "month": 12, "year": 2024},
},
"timeGranularity": "MONTHLY",
"accounts": ["urn:li:sponsoredAccount:123456789"],
"fields": "impressions,clicks,costInLocalCurrency,dateRange",
},
access_token=ACCESS_TOKEN,
version_string=API_VERSION,
)
print("Ad analytics by campaign:")
print(json.dumps(response.elements, indent=2))
print(f"Total results: {response.paging.total}\n")


"""
Get daily analytics for specific campaigns with additional metrics.
"""
response = restli_client.finder(
resource_path=AD_ANALYTICS_RESOURCE,
finder_name="statistics",
query_params={
"pivot": "CAMPAIGN",
"dateRange": {
"start": {"day": 1, "month": 1, "year": 2024},
"end": {"day": 31, "month": 1, "year": 2024},
},
"timeGranularity": "DAILY",
"campaigns": [
"urn:li:sponsoredCampaign:123456789",
"urn:li:sponsoredCampaign:987654321",
],
"fields": "impressions,clicks,costInLocalCurrency,externalWebsiteConversions,dateRange,pivotValues",
},
access_token=ACCESS_TOKEN,
version_string=API_VERSION,
)
print("Daily analytics for specific campaigns:")
print(json.dumps(response.elements, indent=2))
print(f"Total results: {response.paging.total}\n")


"""
Get analytics broken down by creative.
"""
response = restli_client.finder(
resource_path=AD_ANALYTICS_RESOURCE,
finder_name="statistics",
query_params={
"pivot": "CREATIVE",
"dateRange": {
"start": {"day": 1, "month": 1, "year": 2024},
"end": {"day": 31, "month": 1, "year": 2024},
},
"timeGranularity": "ALL",
"campaigns": ["urn:li:sponsoredCampaign:123456789"],
"fields": "impressions,clicks,costInLocalCurrency,pivotValues",
},
access_token=ACCESS_TOKEN,
version_string=API_VERSION,
)
print("Analytics by creative:")
print(json.dumps(response.elements, indent=2))
print(f"Total results: {response.paging.total}\n")