Search code examples
pythonfacebook-graph-apifacebook-ads-apifacebook-insightsfacebook-marketing-api

how to get insights for all campaigns in single query + Facebook marketing api


I want to write query in Python, I want all campaigns performance details in single request.

how to convert below graph api request in Python Query?

/<version>/act_<ACT_ID>/campaigns?fields=insights.fields(actions_results)

I'd tried using below queries, but it is wrong idea to send multiple times to send request to Facebook, and also Facebook blocks User for 30 minutes.

fields = [Insights.Field.cpm,
          Insights.Field.cpp]

class Fb_insights(object):

    def __init__(self, app_id, app_secret, access_token):
        FacebookAdsApi.init(app_id, app_secret, access_token)

        # Add after FacebookAdsApi.init
        me = AdUser(fbid='me')
        self.my_account = me.get_ad_accounts()[0]

    def campaign_reports(self, since, until):
        params = {
           'level': Insights.Level.campaign, 
           'time_range': {
                'since': since,
                'until': until,
            },
        }

        for campaign in self.my_account.get_campaigns():
            for stat in campaign.get_insights(fields=fields,
                                                  params=params):
                print(stat)

Bad thing is I'm sending requests by calling "get_insights()" for each campaign.

UPDATE

I also tried to fetch directly insights, Below code returns only 1 campaign detail while I've 1 active campaigns and 87 Not Delivering campaign, also update level=campaign in params

for insight in self.my_account.get_insights(fields=fields, params=params):
    print insight

Query: By using my updated code, How can I get all delivered and non-delivered campaigns using single query?


Solution

  • To get all ads link in a single request, I've solved my issues with below code.

    class FB(object):
        def __init__(self):
            me = AdUser(fbid='me')
            self.my_account = me.get_ad_accounts()[0]
    
        def fb_creativies(self, since, until):
            """
            This function is used to get destination url
            for each creative object
            """
            fields = [AdCreative.Field.object_story_spec]
            params = {
                'time_range': {
                    'since': since,
                    'until': until,
                },
            }
    
            return self.my_account.get_ad_creatives(fields=fields, params=params)