universal-ads-sdk 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- universal_ads_sdk/__init__.py +11 -0
- universal_ads_sdk/auth.py +124 -0
- universal_ads_sdk/client.py +378 -0
- universal_ads_sdk/exceptions.py +26 -0
- universal_ads_sdk-1.0.0.dist-info/METADATA +350 -0
- universal_ads_sdk-1.0.0.dist-info/RECORD +9 -0
- universal_ads_sdk-1.0.0.dist-info/WHEEL +5 -0
- universal_ads_sdk-1.0.0.dist-info/licenses/LICENSE +21 -0
- universal_ads_sdk-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Universal Ads SDK
|
|
3
|
+
|
|
4
|
+
A Python SDK for interacting with the Universal Ads Third Party API.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .client import UniversalAdsClient
|
|
8
|
+
from .exceptions import UniversalAdsError, AuthenticationError, APIError
|
|
9
|
+
|
|
10
|
+
__version__ = "1.0.0"
|
|
11
|
+
__all__ = ["UniversalAdsClient", "UniversalAdsError", "AuthenticationError", "APIError"]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Authentication utilities for the Universal Ads SDK.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import time
|
|
8
|
+
from typing import Dict, Any
|
|
9
|
+
from urllib.parse import urlparse
|
|
10
|
+
|
|
11
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
12
|
+
from cryptography.hazmat.primitives.asymmetric import ec, utils
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Authenticator:
|
|
16
|
+
"""Handles request authentication and signing for the Universal Ads API."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, api_key: str, private_key_pem: str):
|
|
19
|
+
"""
|
|
20
|
+
Initialize the authenticator.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
api_key: The API key for authentication
|
|
24
|
+
private_key_pem: The private key in PEM format for signing requests
|
|
25
|
+
"""
|
|
26
|
+
self.api_key = api_key
|
|
27
|
+
self.private_key_pem = private_key_pem
|
|
28
|
+
|
|
29
|
+
# Load the private key
|
|
30
|
+
try:
|
|
31
|
+
self.private_key = serialization.load_pem_private_key(
|
|
32
|
+
private_key_pem.encode("utf-8"),
|
|
33
|
+
password=None,
|
|
34
|
+
)
|
|
35
|
+
except Exception as e:
|
|
36
|
+
raise ValueError(f"Invalid private key format: {e}")
|
|
37
|
+
|
|
38
|
+
def create_canonical_request(
|
|
39
|
+
self,
|
|
40
|
+
method: str,
|
|
41
|
+
url: str,
|
|
42
|
+
headers: Dict[str, str],
|
|
43
|
+
timestamp: str,
|
|
44
|
+
body: str = "",
|
|
45
|
+
) -> str:
|
|
46
|
+
"""
|
|
47
|
+
Create a canonical request string for signing.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
method: HTTP method (GET, POST, PUT, etc.)
|
|
51
|
+
url: Full URL of the request
|
|
52
|
+
headers: Request headers
|
|
53
|
+
timestamp: Unix timestamp as string
|
|
54
|
+
body: Request body (empty for GET requests)
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
Canonical request string
|
|
58
|
+
"""
|
|
59
|
+
parsed_url = urlparse(url)
|
|
60
|
+
path = parsed_url.path or "/"
|
|
61
|
+
query = parsed_url.query or ""
|
|
62
|
+
|
|
63
|
+
canonical_headers = f"x-api-key:{headers['x-api-key']}\nx-timestamp:{timestamp}"
|
|
64
|
+
signed_headers = "x-api-key;x-timestamp"
|
|
65
|
+
body = body if body else ""
|
|
66
|
+
|
|
67
|
+
# Match the backend format exactly - method should NOT be uppercase
|
|
68
|
+
canonical_request = (
|
|
69
|
+
f"{method}\n{path}\n{query}\n{canonical_headers}\n{body}\n{signed_headers}"
|
|
70
|
+
)
|
|
71
|
+
return canonical_request
|
|
72
|
+
|
|
73
|
+
def sign_request(self, canonical_request: str) -> str:
|
|
74
|
+
"""
|
|
75
|
+
Sign the canonical request using ECDSA.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
canonical_request: The canonical request string
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
Base64-encoded signature
|
|
82
|
+
"""
|
|
83
|
+
# Hash the canonical request with SHA-256
|
|
84
|
+
hashed = hashlib.sha256(canonical_request.encode("utf-8")).digest()
|
|
85
|
+
|
|
86
|
+
# Sign the digest using ECDSA with Prehashed SHA-256
|
|
87
|
+
signature = self.private_key.sign(
|
|
88
|
+
hashed, ec.ECDSA(utils.Prehashed(hashes.SHA256()))
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Base64 encode the DER-encoded signature
|
|
92
|
+
return base64.b64encode(signature).decode("utf-8")
|
|
93
|
+
|
|
94
|
+
def get_auth_headers(self, method: str, url: str, body: str = "") -> Dict[str, str]:
|
|
95
|
+
"""
|
|
96
|
+
Generate authentication headers for a request.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
method: HTTP method
|
|
100
|
+
url: Request URL
|
|
101
|
+
body: Request body
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
Dictionary of authentication headers
|
|
105
|
+
"""
|
|
106
|
+
timestamp = str(int(time.time()))
|
|
107
|
+
|
|
108
|
+
headers = {
|
|
109
|
+
"x-api-key": self.api_key,
|
|
110
|
+
"x-timestamp": timestamp,
|
|
111
|
+
"x-sdk-version": "1.0.0", # SDK identification flag
|
|
112
|
+
"x-sdk-source": "universal-ads-python-sdk", # SDK identification flag
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
# Create canonical request
|
|
116
|
+
canonical_request = self.create_canonical_request(
|
|
117
|
+
method, url, headers, timestamp, body
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# Sign the request
|
|
121
|
+
signature = self.sign_request(canonical_request)
|
|
122
|
+
headers["x-signature"] = signature
|
|
123
|
+
|
|
124
|
+
return headers
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Main client for the Universal Ads SDK.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Dict, Any, Optional, Union
|
|
7
|
+
import requests
|
|
8
|
+
from requests.adapters import HTTPAdapter
|
|
9
|
+
from urllib3.util.retry import Retry
|
|
10
|
+
|
|
11
|
+
from .auth import Authenticator
|
|
12
|
+
from .exceptions import APIError, AuthenticationError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class UniversalAdsClient:
|
|
16
|
+
"""
|
|
17
|
+
Main client for interacting with the Universal Ads API.
|
|
18
|
+
|
|
19
|
+
This client provides methods for all available API endpoints including
|
|
20
|
+
creative management, media upload, and reporting.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
BASE_URL = "https://api.universalads.com/v1"
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
api_key: str,
|
|
28
|
+
private_key_pem: str,
|
|
29
|
+
base_url: Optional[str] = None,
|
|
30
|
+
timeout: int = 30,
|
|
31
|
+
max_retries: int = 3,
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initialize the Universal Ads client.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
api_key: Your API key
|
|
38
|
+
private_key_pem: Your private key in PEM format
|
|
39
|
+
base_url: Base URL for the API (defaults to production)
|
|
40
|
+
timeout: Request timeout in seconds
|
|
41
|
+
max_retries: Maximum number of retries for failed requests
|
|
42
|
+
"""
|
|
43
|
+
self.base_url = base_url or self.BASE_URL
|
|
44
|
+
self.timeout = timeout
|
|
45
|
+
|
|
46
|
+
# Initialize authenticator
|
|
47
|
+
try:
|
|
48
|
+
self.authenticator = Authenticator(api_key, private_key_pem)
|
|
49
|
+
except Exception as e:
|
|
50
|
+
raise AuthenticationError(f"Failed to initialize authenticator: {e}")
|
|
51
|
+
|
|
52
|
+
# Setup session with retry strategy
|
|
53
|
+
self.session = requests.Session()
|
|
54
|
+
retry_strategy = Retry(
|
|
55
|
+
total=max_retries,
|
|
56
|
+
backoff_factor=1,
|
|
57
|
+
status_forcelist=[429, 500, 502, 503, 504],
|
|
58
|
+
)
|
|
59
|
+
adapter = HTTPAdapter(max_retries=retry_strategy)
|
|
60
|
+
self.session.mount("http://", adapter)
|
|
61
|
+
self.session.mount("https://", adapter)
|
|
62
|
+
|
|
63
|
+
def _make_request(
|
|
64
|
+
self,
|
|
65
|
+
method: str,
|
|
66
|
+
endpoint: str,
|
|
67
|
+
data: Optional[Union[Dict[str, Any], str]] = None,
|
|
68
|
+
params: Optional[Dict[str, Any]] = None,
|
|
69
|
+
) -> Dict[str, Any]:
|
|
70
|
+
"""
|
|
71
|
+
Make an authenticated request to the API.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
method: HTTP method
|
|
75
|
+
endpoint: API endpoint (without base URL)
|
|
76
|
+
data: Request body data
|
|
77
|
+
params: Query parameters
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
Response data as dictionary
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
APIError: If the request fails
|
|
84
|
+
"""
|
|
85
|
+
# Build URL with query parameters for authentication
|
|
86
|
+
url = f"{self.base_url}{endpoint}"
|
|
87
|
+
if params:
|
|
88
|
+
from urllib.parse import urlencode
|
|
89
|
+
|
|
90
|
+
query_string = urlencode(params)
|
|
91
|
+
url = f"{url}?{query_string}"
|
|
92
|
+
|
|
93
|
+
# Prepare body
|
|
94
|
+
body_str = ""
|
|
95
|
+
if data:
|
|
96
|
+
if isinstance(data, str):
|
|
97
|
+
body_str = data
|
|
98
|
+
else:
|
|
99
|
+
body_str = json.dumps(data)
|
|
100
|
+
|
|
101
|
+
# Get authentication headers (using URL with query params)
|
|
102
|
+
headers = self.authenticator.get_auth_headers(method, url, body_str)
|
|
103
|
+
headers["Content-Type"] = "application/json"
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
response = self.session.request(
|
|
107
|
+
method=method,
|
|
108
|
+
url=url,
|
|
109
|
+
headers=headers,
|
|
110
|
+
data=body_str if body_str else None,
|
|
111
|
+
params=None, # Query params already in URL
|
|
112
|
+
timeout=self.timeout,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
# Handle response
|
|
116
|
+
if response.status_code >= 400:
|
|
117
|
+
error_data = {}
|
|
118
|
+
try:
|
|
119
|
+
error_data = response.json()
|
|
120
|
+
except:
|
|
121
|
+
error_data = {"message": response.text}
|
|
122
|
+
|
|
123
|
+
raise APIError(
|
|
124
|
+
message=f"API request failed: {error_data.get('message', 'Unknown error')}",
|
|
125
|
+
status_code=response.status_code,
|
|
126
|
+
response_data=error_data,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# Return JSON response or empty dict for 204
|
|
130
|
+
if response.status_code == 204:
|
|
131
|
+
return {}
|
|
132
|
+
|
|
133
|
+
return response.json()
|
|
134
|
+
|
|
135
|
+
except requests.RequestException as e:
|
|
136
|
+
raise APIError(f"Request failed: {str(e)}")
|
|
137
|
+
|
|
138
|
+
# Creative Management Methods
|
|
139
|
+
|
|
140
|
+
def get_creatives(
|
|
141
|
+
self,
|
|
142
|
+
ad_account_id: Optional[str] = None,
|
|
143
|
+
limit: Optional[int] = None,
|
|
144
|
+
offset: Optional[int] = None,
|
|
145
|
+
sort: Optional[str] = None,
|
|
146
|
+
) -> Dict[str, Any]:
|
|
147
|
+
"""
|
|
148
|
+
Get a list of creatives.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
ad_account_id: Filter by ad account ID
|
|
152
|
+
limit: Maximum number of results to return
|
|
153
|
+
offset: Number of results to skip
|
|
154
|
+
sort: Sort field and direction (e.g., 'id_asc', 'name_desc')
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Dictionary containing the list of creatives
|
|
158
|
+
"""
|
|
159
|
+
params = {}
|
|
160
|
+
if ad_account_id:
|
|
161
|
+
params["ad_account_id"] = ad_account_id
|
|
162
|
+
if limit:
|
|
163
|
+
params["limit"] = limit
|
|
164
|
+
if offset:
|
|
165
|
+
params["offset"] = offset
|
|
166
|
+
if sort:
|
|
167
|
+
params["sort"] = sort
|
|
168
|
+
|
|
169
|
+
return self._make_request("GET", "/creative", params=params)
|
|
170
|
+
|
|
171
|
+
def get_creative(self, creative_id: str) -> Dict[str, Any]:
|
|
172
|
+
"""
|
|
173
|
+
Get a specific creative by ID.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
creative_id: The creative ID
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
Dictionary containing the creative data
|
|
180
|
+
"""
|
|
181
|
+
return self._make_request("GET", f"/creative/{creative_id}")
|
|
182
|
+
|
|
183
|
+
def create_creative(
|
|
184
|
+
self, ad_account_id: str, name: str, media_id: str
|
|
185
|
+
) -> Dict[str, Any]:
|
|
186
|
+
"""
|
|
187
|
+
Create a new creative.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
ad_account_id: The ad account ID
|
|
191
|
+
name: Creative name
|
|
192
|
+
media_id: The media ID to associate with the creative
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
Dictionary containing the created creative data
|
|
196
|
+
"""
|
|
197
|
+
data = {"ad_account_id": ad_account_id, "name": name, "media_id": media_id}
|
|
198
|
+
return self._make_request("POST", "/creative", data=data)
|
|
199
|
+
|
|
200
|
+
def update_creative(
|
|
201
|
+
self, creative_id: str, name: Optional[str] = None, **kwargs
|
|
202
|
+
) -> Dict[str, Any]:
|
|
203
|
+
"""
|
|
204
|
+
Update an existing creative.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
creative_id: The creative ID to update
|
|
208
|
+
name: New creative name
|
|
209
|
+
**kwargs: Additional fields to update
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
Dictionary containing the updated creative data
|
|
213
|
+
"""
|
|
214
|
+
data = {}
|
|
215
|
+
if name is not None:
|
|
216
|
+
data["name"] = name
|
|
217
|
+
data.update(kwargs)
|
|
218
|
+
|
|
219
|
+
return self._make_request("PUT", f"/creative/{creative_id}", data=data)
|
|
220
|
+
|
|
221
|
+
def delete_creative(self, creative_id: str) -> Dict[str, Any]:
|
|
222
|
+
"""
|
|
223
|
+
Delete a creative.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
creative_id: The creative ID to delete
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
Empty dictionary on success
|
|
230
|
+
"""
|
|
231
|
+
return self._make_request("DELETE", f"/creative/{creative_id}")
|
|
232
|
+
|
|
233
|
+
# Media Management Methods
|
|
234
|
+
|
|
235
|
+
def upload_media(
|
|
236
|
+
self, file_path: str, content_type: str, filename: Optional[str] = None
|
|
237
|
+
) -> Dict[str, Any]:
|
|
238
|
+
"""
|
|
239
|
+
Upload media and get a presigned URL for file upload.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
file_path: Path to the file to upload
|
|
243
|
+
content_type: MIME type of the file
|
|
244
|
+
filename: Optional filename (defaults to basename of file_path)
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Dictionary containing upload information including presigned URL
|
|
248
|
+
"""
|
|
249
|
+
import os
|
|
250
|
+
|
|
251
|
+
if not filename:
|
|
252
|
+
filename = os.path.basename(file_path)
|
|
253
|
+
|
|
254
|
+
data = {"filename": filename, "content_type": content_type}
|
|
255
|
+
|
|
256
|
+
return self._make_request("POST", "/media", data=data)
|
|
257
|
+
|
|
258
|
+
def verify_media(self, media_id: str) -> Dict[str, Any]:
|
|
259
|
+
"""
|
|
260
|
+
Verify that a media upload is complete and valid.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
media_id: The media ID to verify
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
Dictionary containing media verification status
|
|
267
|
+
"""
|
|
268
|
+
return self._make_request("POST", f"/media/{media_id}/verify")
|
|
269
|
+
|
|
270
|
+
# Reporting Methods
|
|
271
|
+
|
|
272
|
+
def get_campaign_report(
|
|
273
|
+
self,
|
|
274
|
+
start_date: str,
|
|
275
|
+
end_date: str,
|
|
276
|
+
ad_account_id: Optional[str] = None,
|
|
277
|
+
campaign_ids: Optional[list] = None,
|
|
278
|
+
limit: Optional[int] = None,
|
|
279
|
+
offset: Optional[int] = None,
|
|
280
|
+
) -> Dict[str, Any]:
|
|
281
|
+
"""
|
|
282
|
+
Get campaign performance report.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
start_date: Start date in YYYY-MM-DD format
|
|
286
|
+
end_date: End date in YYYY-MM-DD format
|
|
287
|
+
ad_account_id: Filter by ad account ID
|
|
288
|
+
campaign_ids: List of campaign IDs to include
|
|
289
|
+
limit: Maximum number of results
|
|
290
|
+
offset: Number of results to skip
|
|
291
|
+
|
|
292
|
+
Returns:
|
|
293
|
+
Dictionary containing campaign report data
|
|
294
|
+
"""
|
|
295
|
+
params = {"start_date": start_date, "end_date": end_date}
|
|
296
|
+
|
|
297
|
+
if ad_account_id:
|
|
298
|
+
params["ad_account_id"] = ad_account_id
|
|
299
|
+
if campaign_ids:
|
|
300
|
+
params["campaign_ids"] = campaign_ids
|
|
301
|
+
if limit:
|
|
302
|
+
params["limit"] = limit
|
|
303
|
+
if offset:
|
|
304
|
+
params["offset"] = offset
|
|
305
|
+
|
|
306
|
+
return self._make_request("GET", "/report/campaign", params=params)
|
|
307
|
+
|
|
308
|
+
def get_adset_report(
|
|
309
|
+
self,
|
|
310
|
+
start_date: str,
|
|
311
|
+
end_date: str,
|
|
312
|
+
ad_account_id: Optional[str] = None,
|
|
313
|
+
adset_ids: Optional[list] = None,
|
|
314
|
+
limit: Optional[int] = None,
|
|
315
|
+
offset: Optional[int] = None,
|
|
316
|
+
) -> Dict[str, Any]:
|
|
317
|
+
"""
|
|
318
|
+
Get adset performance report.
|
|
319
|
+
|
|
320
|
+
Args:
|
|
321
|
+
start_date: Start date in YYYY-MM-DD format
|
|
322
|
+
end_date: End date in YYYY-MM-DD format
|
|
323
|
+
ad_account_id: Filter by ad account ID
|
|
324
|
+
adset_ids: List of adset IDs to include
|
|
325
|
+
limit: Maximum number of results
|
|
326
|
+
offset: Number of results to skip
|
|
327
|
+
|
|
328
|
+
Returns:
|
|
329
|
+
Dictionary containing adset report data
|
|
330
|
+
"""
|
|
331
|
+
params = {"start_date": start_date, "end_date": end_date}
|
|
332
|
+
|
|
333
|
+
if ad_account_id:
|
|
334
|
+
params["ad_account_id"] = ad_account_id
|
|
335
|
+
if adset_ids:
|
|
336
|
+
params["adset_ids"] = adset_ids
|
|
337
|
+
if limit:
|
|
338
|
+
params["limit"] = limit
|
|
339
|
+
if offset:
|
|
340
|
+
params["offset"] = offset
|
|
341
|
+
|
|
342
|
+
return self._make_request("GET", "/report/adset", params=params)
|
|
343
|
+
|
|
344
|
+
def get_ad_report(
|
|
345
|
+
self,
|
|
346
|
+
start_date: str,
|
|
347
|
+
end_date: str,
|
|
348
|
+
ad_account_id: Optional[str] = None,
|
|
349
|
+
ad_ids: Optional[list] = None,
|
|
350
|
+
limit: Optional[int] = None,
|
|
351
|
+
offset: Optional[int] = None,
|
|
352
|
+
) -> Dict[str, Any]:
|
|
353
|
+
"""
|
|
354
|
+
Get ad performance report.
|
|
355
|
+
|
|
356
|
+
Args:
|
|
357
|
+
start_date: Start date in YYYY-MM-DD format
|
|
358
|
+
end_date: End date in YYYY-MM-DD format
|
|
359
|
+
ad_account_id: Filter by ad account ID
|
|
360
|
+
ad_ids: List of ad IDs to include
|
|
361
|
+
limit: Maximum number of results
|
|
362
|
+
offset: Number of results to skip
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
Dictionary containing ad report data
|
|
366
|
+
"""
|
|
367
|
+
params = {"start_date": start_date, "end_date": end_date}
|
|
368
|
+
|
|
369
|
+
if ad_account_id:
|
|
370
|
+
params["ad_account_id"] = ad_account_id
|
|
371
|
+
if ad_ids:
|
|
372
|
+
params["ad_ids"] = ad_ids
|
|
373
|
+
if limit:
|
|
374
|
+
params["limit"] = limit
|
|
375
|
+
if offset:
|
|
376
|
+
params["offset"] = offset
|
|
377
|
+
|
|
378
|
+
return self._make_request("GET", "/report/ad", params=params)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Custom exceptions for the Universal Ads SDK.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class UniversalAdsError(Exception):
|
|
7
|
+
"""Base exception for all Universal Ads SDK errors."""
|
|
8
|
+
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AuthenticationError(UniversalAdsError):
|
|
13
|
+
"""Raised when authentication fails."""
|
|
14
|
+
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class APIError(UniversalAdsError):
|
|
19
|
+
"""Raised when an API request fails."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self, message: str, status_code: int = None, response_data: dict = None
|
|
23
|
+
):
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
self.status_code = status_code
|
|
26
|
+
self.response_data = response_data or {}
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: universal-ads-sdk
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python SDK for the Universal Ads Third Party API
|
|
5
|
+
Home-page: https://github.com/Universal-Ads/universal-ads-sdk-python
|
|
6
|
+
Author: Universal Ads
|
|
7
|
+
Author-email: Universal Ads <support@universalads.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
Project-URL: Homepage, https://github.com/universal-ads/universal-ads-sdk-python
|
|
10
|
+
Project-URL: Documentation, https://docs.universalads.com/sdk/python
|
|
11
|
+
Project-URL: Repository, https://github.com/universal-ads/universal-ads-sdk-python
|
|
12
|
+
Project-URL: Bug Tracker, https://github.com/universal-ads/universal-ads-sdk-python/issues
|
|
13
|
+
Keywords: ads,advertising,api,sdk,universal-ads
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
26
|
+
Requires-Python: >=3.8
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Dist: requests>=2.25.0
|
|
30
|
+
Requires-Dist: cryptography>=3.4.0
|
|
31
|
+
Requires-Dist: urllib3>=1.26.0
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: pytest>=6.0; extra == "dev"
|
|
34
|
+
Requires-Dist: pytest-cov>=2.0; extra == "dev"
|
|
35
|
+
Requires-Dist: black>=21.0; extra == "dev"
|
|
36
|
+
Requires-Dist: flake8>=3.8; extra == "dev"
|
|
37
|
+
Requires-Dist: mypy>=0.800; extra == "dev"
|
|
38
|
+
Dynamic: author
|
|
39
|
+
Dynamic: home-page
|
|
40
|
+
Dynamic: license-file
|
|
41
|
+
Dynamic: requires-python
|
|
42
|
+
|
|
43
|
+
# Universal Ads SDK
|
|
44
|
+
|
|
45
|
+
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, and accessing performance reports.
|
|
46
|
+
|
|
47
|
+
## Features
|
|
48
|
+
|
|
49
|
+
- **Creative Management**: Create, read, update, and delete creatives
|
|
50
|
+
- **Media Upload**: Upload and verify media files
|
|
51
|
+
- **Reports**: Access campaign, adset, and ad performance data
|
|
52
|
+
- **Secure Authentication**:
|
|
53
|
+
- **Automatic Retries**: Built-in retry logic for robust API interactions
|
|
54
|
+
- **Type Hints**: Full type annotation support for better development experience
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install universal-ads-sdk
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Quick Start
|
|
63
|
+
|
|
64
|
+
### 1. Initialize the Client
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from universal_ads_sdk import UniversalAdsClient
|
|
68
|
+
|
|
69
|
+
# Initialize the client with your API credentials
|
|
70
|
+
client = UniversalAdsClient(
|
|
71
|
+
api_key="your-api-key",
|
|
72
|
+
private_key_pem="""-----BEGIN PRIVATE KEY-----
|
|
73
|
+
your-private-key-content
|
|
74
|
+
-----END PRIVATE KEY-----"""
|
|
75
|
+
)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### 2. Upload Media
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
# Upload a media file
|
|
82
|
+
upload_info = client.upload_media(
|
|
83
|
+
file_path="/path/to/your/image.jpg",
|
|
84
|
+
content_type="image/jpeg"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
# Use the presigned URL to upload your file
|
|
88
|
+
import requests
|
|
89
|
+
with open("/path/to/your/image.jpg", "rb") as f:
|
|
90
|
+
requests.put(upload_info["upload_url"], data=f)
|
|
91
|
+
|
|
92
|
+
# Verify the upload
|
|
93
|
+
media = client.verify_media(upload_info["media_id"])
|
|
94
|
+
print(f"Media verified: {media['status']}")
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 3. Create a Creative
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
# Create a new creative
|
|
101
|
+
creative = client.create_creative(
|
|
102
|
+
ad_account_id="3d49e08c-465d-4673-a445-d4ba3575f032",
|
|
103
|
+
name="My Creative",
|
|
104
|
+
media_id="cc0f46c7-d9b9-4758-9479-17e1d77c5eea"
|
|
105
|
+
)
|
|
106
|
+
print(f"Created creative: {creative['id']}")
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### 4. Get Performance Reports
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
# Get campaign performance report
|
|
113
|
+
report = client.get_campaign_report(
|
|
114
|
+
start_date="2024-01-01",
|
|
115
|
+
end_date="2024-01-31",
|
|
116
|
+
ad_account_id="3d49e08c-465d-4673-a445-d4ba3575f032"
|
|
117
|
+
)
|
|
118
|
+
print(f"Report contains {len(report['data'])} campaigns")
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## API Reference
|
|
122
|
+
|
|
123
|
+
### Client Initialization
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
UniversalAdsClient(
|
|
127
|
+
api_key: str, # Your API key
|
|
128
|
+
private_key_pem: str, # Your private key in PEM format
|
|
129
|
+
base_url: Optional[str] = None, # API base URL (defaults to production)
|
|
130
|
+
timeout: int = 30, # Request timeout in seconds
|
|
131
|
+
max_retries: int = 3 # Maximum retry attempts
|
|
132
|
+
)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Creative Management
|
|
136
|
+
|
|
137
|
+
#### Get All Creatives
|
|
138
|
+
```python
|
|
139
|
+
creatives = client.get_creatives(
|
|
140
|
+
ad_account_id="account-id", # Optional: filter by account
|
|
141
|
+
limit=50, # Optional: limit results
|
|
142
|
+
offset=0, # Optional: pagination offset
|
|
143
|
+
sort="name_asc" # Optional: sort order
|
|
144
|
+
)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
#### Get Specific Creative
|
|
148
|
+
```python
|
|
149
|
+
creative = client.get_creative("creative-id")
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
#### Create Creative
|
|
153
|
+
```python
|
|
154
|
+
creative = client.create_creative(
|
|
155
|
+
ad_account_id="account-id",
|
|
156
|
+
name="Creative Name",
|
|
157
|
+
media_id="media-id"
|
|
158
|
+
)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
#### Update Creative
|
|
162
|
+
```python
|
|
163
|
+
creative = client.update_creative(
|
|
164
|
+
"creative-id",
|
|
165
|
+
name="New Name"
|
|
166
|
+
)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
#### Delete Creative
|
|
170
|
+
```python
|
|
171
|
+
client.delete_creative("creative-id")
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### Media Management
|
|
175
|
+
|
|
176
|
+
#### Upload Media
|
|
177
|
+
```python
|
|
178
|
+
upload_info = client.upload_media(
|
|
179
|
+
file_path="/path/to/file",
|
|
180
|
+
content_type="image/jpeg",
|
|
181
|
+
filename="optional-filename.jpg" # Optional
|
|
182
|
+
)
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
#### Verify Media
|
|
186
|
+
```python
|
|
187
|
+
media = client.verify_media("media-id")
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Reporting
|
|
191
|
+
|
|
192
|
+
#### Campaign Report
|
|
193
|
+
```python
|
|
194
|
+
report = client.get_campaign_report(
|
|
195
|
+
start_date="2024-01-01",
|
|
196
|
+
end_date="2024-01-31",
|
|
197
|
+
ad_account_id="account-id", # Optional
|
|
198
|
+
campaign_ids=["id1", "id2"], # Optional
|
|
199
|
+
limit=100, # Optional
|
|
200
|
+
offset=0 # Optional
|
|
201
|
+
)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
#### Adset Report
|
|
205
|
+
```python
|
|
206
|
+
report = client.get_adset_report(
|
|
207
|
+
start_date="2024-01-01",
|
|
208
|
+
end_date="2024-01-31",
|
|
209
|
+
ad_account_id="account-id", # Optional
|
|
210
|
+
adset_ids=["id1", "id2"], # Optional
|
|
211
|
+
limit=100, # Optional
|
|
212
|
+
offset=0 # Optional
|
|
213
|
+
)
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
#### Ad Report
|
|
217
|
+
```python
|
|
218
|
+
report = client.get_ad_report(
|
|
219
|
+
start_date="2024-01-01",
|
|
220
|
+
end_date="2024-01-31",
|
|
221
|
+
ad_account_id="account-id", # Optional
|
|
222
|
+
ad_ids=["id1", "id2"], # Optional
|
|
223
|
+
limit=100, # Optional
|
|
224
|
+
offset=0 # Optional
|
|
225
|
+
)
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Error Handling
|
|
229
|
+
|
|
230
|
+
The SDK provides specific exception types for different error scenarios:
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
from universal_ads_sdk import UniversalAdsError, AuthenticationError, APIError
|
|
234
|
+
|
|
235
|
+
try:
|
|
236
|
+
creative = client.create_creative(...)
|
|
237
|
+
except AuthenticationError as e:
|
|
238
|
+
print(f"Authentication failed: {e}")
|
|
239
|
+
except APIError as e:
|
|
240
|
+
print(f"API error {e.status_code}: {e}")
|
|
241
|
+
print(f"Response data: {e.response_data}")
|
|
242
|
+
except UniversalAdsError as e:
|
|
243
|
+
print(f"SDK error: {e}")
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## Configuration
|
|
247
|
+
|
|
248
|
+
### Environment Variables
|
|
249
|
+
|
|
250
|
+
You can also initialize the client using environment variables:
|
|
251
|
+
|
|
252
|
+
```python
|
|
253
|
+
import os
|
|
254
|
+
from universal_ads_sdk import UniversalAdsClient
|
|
255
|
+
|
|
256
|
+
client = UniversalAdsClient(
|
|
257
|
+
api_key=os.getenv("UNIVERSAL_ADS_API_KEY"),
|
|
258
|
+
private_key_pem=os.getenv("UNIVERSAL_ADS_PRIVATE_KEY")
|
|
259
|
+
)
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
### Custom Base URL
|
|
263
|
+
|
|
264
|
+
For testing or development, you can use a custom base URL:
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
client = UniversalAdsClient(
|
|
268
|
+
api_key="your-api-key",
|
|
269
|
+
private_key_pem="your-private-key",
|
|
270
|
+
base_url="https://staging-api.universalads.com/v1"
|
|
271
|
+
)
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
## Authentication
|
|
275
|
+
|
|
276
|
+
The SDK uses request signing for secure API access. Each request is signed with your private key and includes:
|
|
277
|
+
|
|
278
|
+
## Requirements
|
|
279
|
+
|
|
280
|
+
- Python 3.8+
|
|
281
|
+
- requests >= 2.25.0
|
|
282
|
+
- cryptography >= 3.4.0
|
|
283
|
+
- urllib3 >= 1.26.0
|
|
284
|
+
|
|
285
|
+
## Security
|
|
286
|
+
|
|
287
|
+
### API Credentials
|
|
288
|
+
- **Never commit API credentials to version control**
|
|
289
|
+
- Use environment variables for production deployments
|
|
290
|
+
- Test files with credentials are excluded from git via `.gitignore`
|
|
291
|
+
|
|
292
|
+
### Environment Variables (Recommended)
|
|
293
|
+
```bash
|
|
294
|
+
export UNIVERSAL_ADS_API_KEY="your-api-key"
|
|
295
|
+
export UNIVERSAL_ADS_PRIVATE_KEY="your-private-key-pem"
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
```python
|
|
299
|
+
import os
|
|
300
|
+
from universal_ads_sdk import UniversalAdsClient
|
|
301
|
+
|
|
302
|
+
client = UniversalAdsClient(
|
|
303
|
+
api_key=os.getenv("UNIVERSAL_ADS_API_KEY"),
|
|
304
|
+
private_key_pem=os.getenv("UNIVERSAL_ADS_PRIVATE_KEY")
|
|
305
|
+
)
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
## Development
|
|
309
|
+
|
|
310
|
+
### Running Tests
|
|
311
|
+
|
|
312
|
+
The SDK includes test templates in the `tests/` directory. For security, use environment variables:
|
|
313
|
+
|
|
314
|
+
```bash
|
|
315
|
+
# Set up environment variables
|
|
316
|
+
cp env.template .env
|
|
317
|
+
# Edit .env with your credentials
|
|
318
|
+
pip install python-dotenv # Optional, for better .env support
|
|
319
|
+
|
|
320
|
+
# Quick test (basic validation)
|
|
321
|
+
python tests/test_template.py
|
|
322
|
+
|
|
323
|
+
# Comprehensive test (all endpoints)
|
|
324
|
+
python tests/comprehensive_test.py
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
See `tests/README.md` for detailed testing information.
|
|
328
|
+
|
|
329
|
+
For development testing with pytest:
|
|
330
|
+
```bash
|
|
331
|
+
pip install -e ".[dev]"
|
|
332
|
+
pytest
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
### Code Formatting
|
|
336
|
+
|
|
337
|
+
```bash
|
|
338
|
+
black universal_ads_sdk/
|
|
339
|
+
flake8 universal_ads_sdk/
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
## Support
|
|
343
|
+
|
|
344
|
+
- Documentation: [https://developers.universalads.com/](https://developers.universalads.com/)
|
|
345
|
+
- Issues: [GitHub Issues](https://github.com/universal-ads/universal-ads-sdk-python/issues)
|
|
346
|
+
- Email: support+sdk@universalads.com
|
|
347
|
+
|
|
348
|
+
## License
|
|
349
|
+
|
|
350
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
universal_ads_sdk/__init__.py,sha256=H7zA2Vi6Gl512ctDAG9LnD8MP5v1pW0QOETagYkS3DM,321
|
|
2
|
+
universal_ads_sdk/auth.py,sha256=PhGLOa7T8Q4tmomsmStEoX6Aek20EwBX3so9Nj8SIAk,3766
|
|
3
|
+
universal_ads_sdk/client.py,sha256=Oqe1BNAdGPwsmnvxRsQ5NQbuOQcIyfJxyB07dgpvOM0,11405
|
|
4
|
+
universal_ads_sdk/exceptions.py,sha256=HLtCgy2f0dD2z-PSDEZBuuhkd_SqfDPo4YWAp45O9kk,571
|
|
5
|
+
universal_ads_sdk-1.0.0.dist-info/licenses/LICENSE,sha256=nYSDqT56D0wSy02-y8EmITlAWO21sHesx-z8qokSVqA,1070
|
|
6
|
+
universal_ads_sdk-1.0.0.dist-info/METADATA,sha256=hSlE7-27sXwIrIKQ6y1-2alqyk3Cr0psbykcCqPLxDs,9060
|
|
7
|
+
universal_ads_sdk-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
8
|
+
universal_ads_sdk-1.0.0.dist-info/top_level.txt,sha256=xkADXwiFHJvr1vOXV7e7agc8mwkTEtTYBISPYTVCN4Q,18
|
|
9
|
+
universal_ads_sdk-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Universal Ads
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
universal_ads_sdk
|