Thunder Storm
Thunder Storm

Reputation: 121

Facebook Marketing API: retrieving metadata for many Ads via Python

I hope, someone has stumbled over the same issue and might guide me towards a simple solution for my problem.

I want to retrieve regularly some data regarding my Ads on Facebook. Basically, I just want to store some metadata in one of my databases for further reporting purposes. Thus, I want to get AD-ID, AD-name and corresponding ADSET-ID for all my Ads.

I have written this small function in Python:

def get_ad_stats(ad_account):
    """ Pull basic stats for all ads
    Args: 'ad_account' is the Facebook AdAccount object
    Returns: 'fb_ads', a list with basic values
    """
    fb_ads = []
    fb_fields = [
                Ad.Field.id,
                Ad.Field.name,
                Ad.Field.adset_id,
                Ad.Field.created_time,
    ]

    fb_params = {
        'date_preset': 'last_14_days',
    }

    for ad in ad_account.get_ads(fields = fb_fields, params = fb_params):
        fb_ads.append({
            'id':                   ad[Ad.Field.id],
            'name':                 ad[Ad.Field.name],
            'adset_id':             ad[Ad.Field.adset_id],
            'created_time':         datetime.datetime.strptime(ad[Ad.Field.created_time], "%Y-%m-%dT%H:%M:%S+0000"),
        })

    return (fb_ads)

Similar functions for Campaign- and AdSet-data work fine. But for Ads I am always reaching a user request limit: "(#17) User request limit reached".

I do have an API-access level of "BASIC" and we're talking here about 12,000 Ads. And, unfortunately, async-calls seem to work only for the Insights-edge.

Is there a way to avoid the user request limit, e.g. by limiting the API-request to only those Ads which have been changed/newly created after a specific date or so?

Upvotes: 3

Views: 1198

Answers (1)

Thunder Storm
Thunder Storm

Reputation: 121

Ok, sacrificing the 'created_time' field, I have realized I could use the Insights-edge for that. Here is a revised code for the same function which is now using async-calls and a delay between calls:

def get_ad_stats(ad_account):
    """ Pull basic stats for all ads
    Args: 'ad_account' is the Facebook AdAccount object
    Returns: 'fb_ads', a list with basic values
    """
    fb_ads = []

    fb_params = {
        'date_preset': 'last_14_days',
        'level': 'ad',
    }

    fb_fields = [
        'ad_id',
        'ad_name',
        'adset_id',
    ]

    async_job = ad_account.get_insights(fields = fb_fields, params = fb_params, async=True)
    async_job.remote_read()

    while async_job['async_percent_completion'] < 100:
        time.sleep(1)
        async_job.remote_read()

    for ad in async_job.get_result():
        fb_ads.append({
            'id':                   ad['ad_id'],
            'name':                 ad['ad_name'],
            'adset_id':             ad['adset_id'],
        })

    return (fb_ads)

Upvotes: 2

Related Questions