Skip to main content

Python SDK for the Universal Ads Third Party API

Project description

Universal Ads SDK

A Python SDK for interacting with the Universal Ads Third Party API. This SDK provides a simple and intuitive interface for managing creatives, uploading media, creating custom segments, and accessing performance reports.

Features

  • Creative Management: Create, read, update, and delete creatives
  • Media Upload: Upload and verify media files
  • Segment Management: Create and manage custom segments for targeted advertising
  • Reports: Access campaign, adset, and ad performance data
  • Secure Authentication: Request signing with private key authentication
  • Automatic Retries: Built-in retry logic for robust API interactions
  • Type Hints: Full type annotation support for better development experience

Installation

pip install universal-ads-sdk

Quick Start

1. Initialize the Client

from universal_ads_sdk import UniversalAdsClient

# Initialize the client with your API credentials
client = UniversalAdsClient(
    api_key="your-api-key",
    private_key_pem="""-----BEGIN PRIVATE KEY-----
your-private-key-content
-----END PRIVATE KEY-----"""
)

2. Upload Media

# Upload a media file
upload_info = client.upload_media(
    file_path="/path/to/your/image.jpg",
    content_type="image/jpeg"
)

# Use the presigned URL to upload your file
import requests
with open("/path/to/your/image.jpg", "rb") as f:
    requests.put(upload_info["upload_url"], data=f)

# Verify the upload
media = client.verify_media(upload_info["media_id"])
print(f"Media verified: {media['status']}")

3. Create a Creative

# Create a new creative
creative = client.create_creative(
    adaccount_id="3d49e08c-465d-4673-a445-d4ba3575f032",
    name="My Creative",
    media_id="cc0f46c7-d9b9-4758-9479-17e1d77c5eea"
)
print(f"Created creative: {creative['id']}")

4. Create a Custom Segment

# First, upload a CSV or TXT file containing user identifiers (one per row)
upload_info = client.upload_media(
    file_path="/path/to/users.csv",
    content_type="text/csv"
)

# Upload the file to the presigned URL
import requests
with open("/path/to/users.csv", "rb") as f:
    requests.put(upload_info["upload_url"], data=f)

# Verify the upload
media = client.verify_media(upload_info["media_id"])

# Create a new custom segment using the uploaded media
segment = client.create_segment(
    adaccount_id="3d49e08c-465d-4673-a445-d4ba3575f032",
    media_id=upload_info["media_id"],
    name="My Custom Segment",
    segment_type="custom",
    description="A segment for targeted advertising"
)
print(f"Created segment: {segment['id']}")

# Alternatively, add users programmatically (for smaller lists)
client.update_segment_users(
    segment_id=segment["id"],
    users=["user@example.com", "another@example.com"],
    remove=False
)

5. Get Performance Reports

# Get campaign performance report
report = client.get_campaign_report(
    start_date="2024-01-01",
    end_date="2024-01-31",
    adaccount_id="3d49e08c-465d-4673-a445-d4ba3575f032"
)
print(f"Report contains {len(report['data'])} campaigns")

API Reference

Client Initialization

UniversalAdsClient(
    api_key: str,                    # Your API key
    private_key_pem: str,            # Your private key in PEM format
    base_url: Optional[str] = None,  # API base URL (defaults to production)
    timeout: int = 30,               # Request timeout in seconds
    max_retries: int = 3             # Maximum retry attempts
)

Creative Management

Get All Creatives

creatives = client.get_creatives(
    adaccount_id="account-id",  # Optional: filter by account
    limit=50,                    # Optional: limit results
    offset=0,                    # Optional: pagination offset
    sort="name_asc"              # Optional: sort order
)

Get Specific Creative

creative = client.get_creative("creative-id")

Create Creative

creative = client.create_creative(
    adaccount_id="account-id",
    name="Creative Name",
    media_id="media-id"
)

Update Creative

creative = client.update_creative(
    "creative-id",
    name="New Name"
)

Delete Creative

client.delete_creative("creative-id")

Media Management

Upload Media

upload_info = client.upload_media(
    file_path="/path/to/file",
    content_type="image/jpeg",
    filename="optional-filename.jpg"  # Optional
)

Verify Media

media = client.verify_media("media-id")

Reporting

Campaign Report

report = client.get_campaign_report(
    start_date="2024-01-01",
    end_date="2024-01-31",
    adaccount_id="account-id",      # Optional
    campaign_ids=["id1", "id2"],     # Optional
    limit=100,                       # Optional
    offset=0                         # Optional
)

Adset Report

report = client.get_adset_report(
    start_date="2024-01-01",
    end_date="2024-01-31",
    adaccount_id="account-id",      # Optional
    adset_ids=["id1", "id2"],        # Optional
    limit=100,                       # Optional
    offset=0                         # Optional
)

Ad Report

report = client.get_ad_report(
    start_date="2024-01-01",
    end_date="2024-01-31",
    adaccount_id="account-id",      # Optional
    ad_ids=["id1", "id2"],           # Optional
    limit=100,                       # Optional
    offset=0                         # Optional
)

Segment Management

Segment File Format Requirements

When creating or extending segments, you need to upload a media file containing user data. The file must meet these requirements:

  • File Format: CSV or TXT files only
  • Structure: Single column format (one identifier per row)
  • Encoding: UTF-8 encoding
  • File Size: Maximum 25MB (use large_files=True for larger files)
  • Content:
    • For email segments: Each row must contain a valid email address
    • For other segment types: Each row contains a single identifier (e.g., IP address, Blockgraph ID, Experian LUID, Liveramp ID)

Example CSV file for email segments:

user1@example.com
user2@example.com
user3@example.com

Example TXT file for email segments:

user1@example.com
user2@example.com
user3@example.com

Upload Process:

  1. Upload your file using the upload_media() method to get a media_id
  2. Use the media_id when creating or extending a segment
  3. The file will be validated automatically

Get All Segments

segments = client.get_segments(
    adaccount_id="account-id",       # Required
    name="Segment Name",             # Optional: filter by name
    status="active",                 # Optional: filter by status
    limit=50,                        # Optional: limit results
    offset=0,                        # Optional: pagination offset
    sort="name_asc"                  # Optional: sort order
)

Get Specific Segment

segment = client.get_segment("segment-id")

Create Segment

# Note: media_id must reference a CSV or TXT file uploaded via upload_media()
# The file must contain one identifier per row (see Segment File Format Requirements above)
segment = client.create_segment(
    adaccount_id="account-id",
    media_id="media-id",                # From upload_media() response
    name="Segment Name",
    segment_type="custom",
    description="Optional description",  # Optional
    large_files=False                    # Optional: set True for files > 25MB
)

Update Segment

segment = client.update_segment(
    "segment-id",
    name="Updated Segment Name",
    description="Updated description"    # Optional
)

Extend Segment

# Add additional media to an existing segment
# Note: media_id must reference a CSV or TXT file uploaded via upload_media()
client.extend_segment(
    segment_id="segment-id",
    media_id="new-media-id",            # From upload_media() response
    large_files=False                    # Optional: set True for files > 25MB
)

Update Segment Users

# Add users to a segment
client.update_segment_users(
    segment_id="segment-id",
    users=["user1@example.com", "user2@example.com"],
    remove=False  # Set to True to remove users instead
)

# Remove users from a segment
client.update_segment_users(
    segment_id="segment-id",
    users=["user1@example.com"],
    remove=True
)

Delete Segment

client.delete_segment("segment-id")

Error Handling

The SDK provides specific exception types for different error scenarios:

from universal_ads_sdk import UniversalAdsError, AuthenticationError, APIError

try:
    creative = client.create_creative(...)
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except APIError as e:
    print(f"API error {e.status_code}: {e}")
    print(f"Response data: {e.response_data}")
except UniversalAdsError as e:
    print(f"SDK error: {e}")

Configuration

Environment Variables

You can also initialize the client using environment variables:

import os
from universal_ads_sdk import UniversalAdsClient

client = UniversalAdsClient(
    api_key=os.getenv("UNIVERSAL_ADS_API_KEY"),
    private_key_pem=os.getenv("UNIVERSAL_ADS_PRIVATE_KEY")
)

Custom Base URL

For testing or development, you can use a custom base URL:

client = UniversalAdsClient(
    api_key="your-api-key",
    private_key_pem="your-private-key",
    base_url="https://staging-api.universalads.com/v1"
)

Authentication

The SDK uses request signing for secure API access. Each request is signed with your private key and includes:

Requirements

  • Python 3.8+
  • requests >= 2.25.0
  • cryptography >= 3.4.0
  • urllib3 >= 1.26.0

Security

API Credentials

  • Never commit API credentials to version control
  • Use environment variables for production deployments
  • Test files with credentials are excluded from git via .gitignore

Environment Variables (Recommended)

export UNIVERSAL_ADS_API_KEY="your-api-key"
export UNIVERSAL_ADS_PRIVATE_KEY="your-private-key-pem"
import os
from universal_ads_sdk import UniversalAdsClient

client = UniversalAdsClient(
    api_key=os.getenv("UNIVERSAL_ADS_API_KEY"),
    private_key_pem=os.getenv("UNIVERSAL_ADS_PRIVATE_KEY")
)

Development

Running Tests

The SDK includes test templates in the tests/ directory. For security, use environment variables:

# Set up environment variables
cp env.template .env
# Edit .env with your credentials
pip install python-dotenv  # Optional, for better .env support

# Quick test (basic validation)
python tests/test_template.py

# Comprehensive test (all endpoints)
python tests/comprehensive_test.py

See tests/README.md for detailed testing information.

For development testing with pytest:

pip install -e ".[dev]"
pytest

Code Formatting

black universal_ads_sdk/
flake8 universal_ads_sdk/

Support

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

universal_ads_sdk-1.1.0.tar.gz (17.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

universal_ads_sdk-1.1.0-py3-none-any.whl (15.4 kB view details)

Uploaded Python 3

File details

Details for the file universal_ads_sdk-1.1.0.tar.gz.

File metadata

  • Download URL: universal_ads_sdk-1.1.0.tar.gz
  • Upload date:
  • Size: 17.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for universal_ads_sdk-1.1.0.tar.gz
Algorithm Hash digest
SHA256 90184d6a29108e872f920fd6321e87cb38bd3b6f77f591c27147f067dfb1cf09
MD5 c4cd62fccae5c7c3e4321368c44ae694
BLAKE2b-256 d8fccd429099faa1db5939dd5eb0b4f886c0a599d74bf567ef8ef9d70a27e7a6

See more details on using hashes here.

File details

Details for the file universal_ads_sdk-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for universal_ads_sdk-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 afa499253fbb5edc0a4a5d5ca3cc7201160e8816e870124f39aca8926f478ed0
MD5 4f30da72aeeab6d7bd88c75bea004692
BLAKE2b-256 62d9c779632ff7ba56fbec3788b673bf19bbe65d06c837e019d19d9cd9816419

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page