Hey there, fellow developer! Ready to dive into the world of Twitter Ads API? You're in for a treat. This guide will walk you through building a robust integration that'll have you managing campaigns, creating ads, and pulling analytics like a pro. Let's get started!
Before we jump in, make sure you've got:
First things first, let's tackle authentication. We'll be using OAuth 1.0a here. Don't worry, it's not as scary as it sounds!
from requests_oauthlib import OAuth1Session consumer_key = 'your_consumer_key' consumer_secret = 'your_consumer_secret' access_token = 'your_access_token' access_token_secret = 'your_access_token_secret' oauth = OAuth1Session( consumer_key, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret )
Let's keep things organized:
twitter_ads_api/
├── main.py
├── auth.py
├── api_client.py
├── campaign_manager.py
├── ad_manager.py
├── analytics.py
└── utils.py
You'll need requests
, requests_oauthlib
, and json
libraries. Go ahead and install them if you haven't already.
Here's where the magic happens:
# api_client.py import requests BASE_URL = 'https://ads-api.twitter.com/8' class TwitterAdsAPI: def __init__(self, oauth): self.oauth = oauth def make_request(self, method, endpoint, params=None, data=None): url = f"{BASE_URL}/{endpoint}" response = self.oauth.request(method, url, params=params, json=data) response.raise_for_status() return response.json()
Now you can make requests like a boss:
api = TwitterAdsAPI(oauth) accounts = api.make_request('GET', 'accounts')
Always be prepared:
from time import sleep def make_request_with_retry(api, method, endpoint, max_retries=3, **kwargs): for attempt in range(max_retries): try: return api.make_request(method, endpoint, **kwargs) except requests.exceptions.HTTPError as e: if e.response.status_code == 429: # Rate limit exceeded sleep(60) # Wait for a minute before retrying elif attempt == max_retries - 1: raise
Let's create a campaign:
def create_campaign(api, account_id, name, funding_instrument_id, start_time, daily_budget): endpoint = f'accounts/{account_id}/campaigns' data = { 'name': name, 'funding_instrument_id': funding_instrument_id, 'start_time': start_time, 'daily_budget_amount_local_micro': daily_budget } return api.make_request('POST', endpoint, data=data)
Targeting is crucial. Here's a quick example:
def set_targeting(api, account_id, line_item_id, targeting_criteria): endpoint = f'accounts/{account_id}/targeting_criteria' data = { 'line_item_id': line_item_id, 'targeting_criteria': targeting_criteria } return api.make_request('POST', endpoint, data=data)
Creating an ad is a breeze:
def create_tweet(api, account_id, text): endpoint = f'accounts/{account_id}/tweet' data = {'text': text} return api.make_request('POST', endpoint, data=data)
Get those sweet, sweet insights:
def get_campaign_analytics(api, account_id, campaign_id, start_date, end_date): endpoint = f'stats/accounts/{account_id}' params = { 'entity': 'CAMPAIGN', 'entity_ids': campaign_id, 'start_date': start_date, 'end_date': end_date, 'metric_groups': 'ENGAGEMENT' } return api.make_request('GET', endpoint, params=params)
Unit testing is your friend:
import unittest from unittest.mock import Mock class TestTwitterAdsAPI(unittest.TestCase): def setUp(self): self.api = TwitterAdsAPI(Mock()) def test_create_campaign(self): self.api.make_request = Mock(return_value={'data': {'id': '123'}}) result = create_campaign(self.api, 'account_id', 'Test Campaign', 'funding_id', '2023-06-01', 1000000) self.assertEqual(result['data']['id'], '123')
And there you have it! You're now equipped to build a killer Twitter Ads API integration. Remember, practice makes perfect, so don't be afraid to experiment and push the boundaries. Happy coding!