skip to Main Content

I’m using the Facebook Business API in order to collect data from my Ad Account. I would like to make an accounting script by getting spend amount on Facebook Ads everyday and put it automatically in a Google Sheet.

Currently, I managed to collect the data from my account. The problem is that I was expecting to have it in JSON to access the data I need to pass it into a class that would send it to Google Sheet.

But it seems to be a Cursor element and I have no idea how to pick the exact data I want from this object and I have no idea how to manipulate it by using Python.

Here’s my code :

def GetParam():
    
      access_token = 'EAACWg1HnQekBAA0SmZA9wcYPfxio3K2U24Jp1OmfaXAzRHPBwEe3FxAxBg0L8EaLamvGHZAfNp3chYZAZCpHObRdU2En6YGWyqGRPuPRmqN2ZCeg2ZA9F9ybwythM1FCR23hOiG571kq7wXOMv6yWYPRljAJalozBVZCSeZCFCjHmHKI97u9eqPYzucHU5ZBLNEhZBoo1BvPPh9QZDZD'
      ad_account_id = 'act_2270297423225223'
      app_secret = 'b5731d443c5dca5b3412e385004816fa'
      app_id = '165490758992361'
      FacebookAdsApi.init(access_token=access_token)
    
    
      today = date.today()
      today_format = today.strftime("%Y-%m-%d")
    
      fields = [
          'impressions',
          'spend',
          'cpm',
      ]
      params = {
          'time_range': {'since':today_format,'until': today_format},
          'filtering': [],
          'level': 'account',
          'breakdowns': [],
      }
    
      return (AdAccount(ad_account_id).get_insights(
          fields=fields,
          params=params,
      ))
    
    reponse = GetParam()
    print(reponse)

And here you have the result of the print()

[<AdsInsights> {
"cpm": "1.92389",
"date_start": "2021-08-18",
"date_stop": "2021-08-18",
"impressions": "946",
"spend": "1.82"
}]
[Finished in 448ms]

I would like to focus on the ‘spend’ element.

Something like:

spend_amount = reponse.AdsInsights[spend]

I hope it’s clear enough, I’m a complete beginner and maybe the answer is absolutely obvious but I can’t find it..

Thank you so much.

2

Answers


  1. Chosen as BEST ANSWER

    I finally found the answer, here it is in case you face the same problem :

    amount_spend = reponse[0]['spend']
    print(amount_spend)
    

    Here's the result :

    1.82
    

    The [0] allow us to access the first element of the cursor Object which is an object called 'AdsInsights'. Then it work like a dictionnary to access the data you need.


  2. Since the response can contain a big number of data the API methods of the wrapper returns you a Iterator so you can iterate through the whole data in the loop.

    for insight in response:
        amount_spend = insight['spend']
        print(f'Amount spent {amount_spend}')
    

    But you always can convert iterator into the list, e.g.

    response = list(response)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search