A Python client for Apple Search Ads API v5
Project description
Apple Search Ads Python Client
A Python client library for Apple Search Ads API v5, providing a simple and intuitive interface for managing and reporting on Apple Search Ads campaigns.
Features
- 🔐 OAuth2 authentication with JWT
- 📊 Campaign performance reporting
- 🏢 Multi-organization support
- 💰 Spend tracking by app
- ⚡ Built-in rate limiting
- 🐼 Pandas DataFrames for easy data manipulation
- 🔄 Automatic token refresh
- 🎯 Type hints for better IDE support
- ✅ 100% test coverage
Installation
pip install apple-search-ads-client
Quick Start
from apple_search_ads import AppleSearchAdsClient
# Initialize the client
client = AppleSearchAdsClient(
client_id="your_client_id",
team_id="your_team_id",
key_id="your_key_id",
private_key_path="/path/to/private_key.p8"
)
# Get all campaigns
campaigns = client.get_campaigns()
# Get daily spend for the last 30 days
spend_df = client.get_daily_spend(days=30)
print(spend_df)
Authentication
Prerequisites
- An Apple Search Ads account with API access
- API credentials from the Apple Search Ads UI:
- Client ID
- Team ID
- Key ID
- Private key file (.p8)
Setting up credentials
You can provide credentials in three ways:
1. Direct parameters (recommended)
client = AppleSearchAdsClient(
client_id="your_client_id",
team_id="your_team_id",
key_id="your_key_id",
private_key_path="/path/to/private_key.p8"
)
2. Environment variables
export APPLE_SEARCH_ADS_CLIENT_ID="your_client_id"
export APPLE_SEARCH_ADS_TEAM_ID="your_team_id"
export APPLE_SEARCH_ADS_KEY_ID="your_key_id"
export APPLE_SEARCH_ADS_PRIVATE_KEY_PATH="/path/to/private_key.p8"
client = AppleSearchAdsClient() # Will use environment variables
3. Private key content
# Useful for environments where file access is limited
with open("private_key.p8", "r") as f:
private_key_content = f.read()
client = AppleSearchAdsClient(
client_id="your_client_id",
team_id="your_team_id",
key_id="your_key_id",
private_key_content=private_key_content
)
Usage Examples
Get all organizations
# List all organizations you have access to
orgs = client.get_all_organizations()
for org in orgs:
print(f"{org['orgName']} - {org['orgId']}")
Get campaign performance report
from datetime import datetime, timedelta
# Get campaign performance for the last 7 days
end_date = datetime.now()
start_date = end_date - timedelta(days=7)
report_df = client.get_campaign_report(
start_date=start_date,
end_date=end_date,
granularity="DAILY" # Options: DAILY, WEEKLY, MONTHLY
)
# Display key metrics
print(report_df[['date', 'campaign_name', 'spend', 'installs', 'taps']])
Track spend by app
# Get daily spend grouped by app
app_spend_df = client.get_daily_spend_by_app(
start_date="2024-01-01",
end_date="2024-01-31",
fetch_all_orgs=True # Fetch from all organizations
)
# Group by app and sum
app_totals = app_spend_df.groupby('app_id').agg({
'spend': 'sum',
'installs': 'sum',
'impressions': 'sum'
}).round(2)
print(app_totals)
Get campaigns from all organizations
# Fetch campaigns across all organizations
all_campaigns = client.get_all_campaigns()
# Filter active campaigns
active_campaigns = [c for c in all_campaigns if c['status'] == 'ENABLED']
print(f"Found {len(active_campaigns)} active campaigns across all orgs")
Working with specific organization
# Get campaigns for a specific org
org_id = "123456"
campaigns = client.get_campaigns(org_id=org_id)
# The client will use this org for subsequent requests
Working with ad groups
# Get ad groups for a campaign
campaign_id = "1234567890"
adgroups = client.get_adgroups(campaign_id)
for adgroup in adgroups:
print(f"Ad Group: {adgroup['name']} (Status: {adgroup['status']})")
API Reference
Client initialization
AppleSearchAdsClient(
client_id: Optional[str] = None,
team_id: Optional[str] = None,
key_id: Optional[str] = None,
private_key_path: Optional[str] = None,
private_key_content: Optional[str] = None,
org_id: Optional[str] = None
)
Methods
Organizations
get_all_organizations()- Get all organizationsget_campaigns(org_id: Optional[str] = None)- Get campaigns for an organizationget_all_campaigns()- Get campaigns from all organizations
Reporting
get_campaign_report(start_date, end_date, granularity="DAILY")- Get campaign performance reportget_daily_spend(days=30, fetch_all_orgs=True)- Get daily spend for the last N daysget_daily_spend_with_dates(start_date, end_date, fetch_all_orgs=True)- Get daily spend for date rangeget_daily_spend_by_app(start_date, end_date, fetch_all_orgs=True)- Get spend grouped by app
Campaign Management
get_campaigns_with_details(fetch_all_orgs=True)- Get campaigns with app detailsget_adgroups(campaign_id)- Get ad groups for a specific campaign
DataFrame Output
All reporting methods return pandas DataFrames for easy data manipulation:
# Example: Calculate weekly totals
daily_spend = client.get_daily_spend(days=30)
daily_spend['week'] = pd.to_datetime(daily_spend['date']).dt.isocalendar().week
weekly_totals = daily_spend.groupby('week')['spend'].sum()
Rate Limiting
The client includes built-in rate limiting to respect Apple's API limits (10 requests per second). You don't need to implement any additional rate limiting.
Error Handling
from apple_search_ads.exceptions import (
AuthenticationError,
RateLimitError,
OrganizationNotFoundError
)
try:
campaigns = client.get_campaigns()
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except RateLimitError as e:
print(f"Rate limit exceeded: {e}")
except Exception as e:
print(f"An error occurred: {e}")
Best Practices
- Reuse client instances: Create one client and reuse it for multiple requests
- Use date ranges wisely: Large date ranges may result in slower responses
- Cache organization IDs: If working with specific orgs frequently, cache their IDs
- Monitor rate limits: Although built-in rate limiting is included, be mindful of your usage
- Use DataFrame operations: Leverage pandas for data aggregation and analysis
Requirements
- Python 3.8 or higher
- See
requirements.txtfor package dependencies
Testing
This project maintains 100% test coverage. The test suite includes:
- Unit tests with mocked API responses
- Exception handling tests
- Edge case coverage
- Legacy API format compatibility tests
- Comprehensive integration tests
Running Tests
# Run all tests with coverage report
pytest tests -v --cov=apple_search_ads --cov-report=term-missing
# Run tests in parallel for faster execution
pytest tests -n auto
# Generate HTML coverage report
pytest tests --cov=apple_search_ads --cov-report=html
# Run integration tests (requires credentials)
pytest tests/test_integration.py -v
For detailed testing documentation, see TESTING.md.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 🐛 Issues: GitHub Issues
- 📖 Documentation: Read the Docs
Changelog
See CHANGELOG.md for a list of changes.
Acknowledgments
- Apple for providing the Search Ads API
- The Python community for excellent libraries used in this project
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file apple_search_ads_client-1.0.7.tar.gz.
File metadata
- Download URL: apple_search_ads_client-1.0.7.tar.gz
- Upload date:
- Size: 23.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cdbb0ff12818a5029aa3b1e41dc74668c79ea1832f5423e22b6dcd69c00f1f30
|
|
| MD5 |
c67cf804917aa9ccc4cfc7298d0eac5e
|
|
| BLAKE2b-256 |
1817cd65014a9d9049a0eee97a5fe6c590c8a9ed2ec36933290d14d8401e8732
|
File details
Details for the file apple_search_ads_client-1.0.7-py3-none-any.whl.
File metadata
- Download URL: apple_search_ads_client-1.0.7-py3-none-any.whl
- Upload date:
- Size: 11.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ddefe72028efba33b650c3829b5df788d7701fdba30e2a3414cdf9e8bf657d62
|
|
| MD5 |
c4d691fb14992d27f41f383c72683c86
|
|
| BLAKE2b-256 |
8cd946fc9edd89a0347e27ed788e4819e56174c190ff787fe3357829187f86fa
|