Back

Step by Step Guide to Building an Instagram Ads API Integration in Python

Aug 3, 2024 • 6 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Instagram Ads API? You're in for a treat. This guide will walk you through building a robust integration that'll have you creating and managing Instagram ad campaigns like a pro. Let's get cracking!

Prerequisites

Before we jump in, make sure you've got these basics covered:

  • Python 3.7+
  • requests library
  • An Instagram Developer account
  • Access token (you know the drill)

Setting Up Your Dev Environment

First things first, let's get your environment ready:

pip install requests

Now, let's set up those API credentials:

import os os.environ['INSTAGRAM_ACCESS_TOKEN'] = 'your_access_token_here'

Basic API Connection

Time to test the waters:

import requests BASE_URL = 'https://graph.facebook.com/v12.0/' ACCESS_TOKEN = os.environ['INSTAGRAM_ACCESS_TOKEN'] response = requests.get(f"{BASE_URL}me/accounts?access_token={ACCESS_TOKEN}") print(response.json())

If you see your account info, you're golden!

Core Functionality Implementation

Creating a Campaign

Let's kick things off with a new campaign:

def create_campaign(name, objective): endpoint = f"{BASE_URL}act_<AD_ACCOUNT_ID>/campaigns" params = { 'name': name, 'objective': objective, 'status': 'PAUSED', 'access_token': ACCESS_TOKEN } response = requests.post(endpoint, params=params) return response.json() campaign = create_campaign('My Awesome Campaign', 'REACH') print(campaign)

Managing Ad Sets

Now for the ad sets:

def create_ad_set(campaign_id, name, daily_budget, start_time, end_time): endpoint = f"{BASE_URL}act_<AD_ACCOUNT_ID>/adsets" params = { 'campaign_id': campaign_id, 'name': name, 'daily_budget': daily_budget, 'start_time': start_time, 'end_time': end_time, 'access_token': ACCESS_TOKEN } response = requests.post(endpoint, params=params) return response.json() ad_set = create_ad_set(campaign['id'], 'My First Ad Set', 1000, '2023-06-01T00:00:00+0000', '2023-06-30T23:59:59+0000') print(ad_set)

Creating and Uploading Ad Creatives

Time to get creative:

def create_ad_creative(name, image_url, caption): endpoint = f"{BASE_URL}act_<AD_ACCOUNT_ID>/adcreatives" params = { 'name': name, 'object_story_spec': { 'instagram_actor_id': '<INSTAGRAM_ACCOUNT_ID>', 'link_data': { 'image_url': image_url, 'caption': caption, 'link': 'https://your-website.com' } }, 'access_token': ACCESS_TOKEN } response = requests.post(endpoint, json=params) return response.json() creative = create_ad_creative('Summer Sale Creative', 'https://example.com/image.jpg', 'Check out our summer sale!') print(creative)

Launching Ads

The moment of truth:

def create_ad(name, adset_id, creative_id): endpoint = f"{BASE_URL}act_<AD_ACCOUNT_ID>/ads" params = { 'name': name, 'adset_id': adset_id, 'creative': {'creative_id': creative_id}, 'status': 'PAUSED', 'access_token': ACCESS_TOKEN } response = requests.post(endpoint, params=params) return response.json() ad = create_ad('My First Ad', ad_set['id'], creative['id']) print(ad)

Handling API Responses

Always check those responses:

def handle_response(response): if response.status_code == 200: return response.json() else: print(f"Error: {response.status_code}") print(response.text) return None

Advanced Features

Want to get fancy? Try these:

def set_targeting(adset_id, countries, age_min, age_max): endpoint = f"{BASE_URL}{adset_id}" params = { 'targeting': { 'geo_locations': {'countries': countries}, 'age_min': age_min, 'age_max': age_max }, 'access_token': ACCESS_TOKEN } response = requests.post(endpoint, json=params) return handle_response(response) targeting = set_targeting(ad_set['id'], ['US'], 18, 65) print(targeting)

Best Practices and Optimization

  • Cache your access token (but refresh it regularly)
  • Batch your API calls when possible
  • Use the fields parameter to limit data returned

Testing and Debugging

Always test your API calls:

import unittest class TestInstagramAdsAPI(unittest.TestCase): def test_create_campaign(self): campaign = create_campaign('Test Campaign', 'REACH') self.assertIsNotNone(campaign['id']) if __name__ == '__main__': unittest.main()

Conclusion

And there you have it! You're now equipped to create some killer Instagram ad campaigns programmatically. Remember, the API is your playground – don't be afraid to experiment and push its limits. Happy coding!