pythonfacebook-graph-apipython-requestsfacebook-insights

Any way to access DAYWISE Facebook ad insights using python and add the response data to an mysql database table?


I was able to access the ads using Postman API and got a python-requests code using the 'Code' option from the Postman app. But the time_increment is working in a few cases. When the time_increment clause works I got a JSON response which I'm unable to convert into a pandas dataframe.

My code looks like this:

import requests

url = "https://graph.facebook.com/v5.0/act_<------id------>/insights?fields=campaign_id,campaign_name,clicks,unique_clicks,reach,spend,impressions,cost_per_unique_click,purchase_roas,website_purchase_roas&time_range={\"since\":\"2019-12-01\",\"until\":\"2019-12-07\"}&time_increment(1)&limit(200)"

payload = {}
headers = {
  'Authorization': 'Bearer <access_token>'
}

response = requests.request("GET", url, headers=headers, data = payload)

res = response.json()
print(res)

When I run the above code I don't get the needed columns like campaign_id, campaign_name, etc. And neither the time_increment clause works.

Any solution is highly appreciated. Please! I was stuck here for the good part of the last week.

My output is :

{
    "data": [
        {
            "clicks": "45547",
            "unique_clicks": "63257",
            "reach": "4269850",
            "spend": "69403.83",
            "impressions": "8525031",
            "cost_per_unique_click": "13.57562",
            "purchase_roas": [
                {
                    "action_type": "xxxxxxxxx",
                    "value": "1.571284"
                }
            ],
            "website_purchase_roas": [
                {
                    "action_type": "yyyyyy.zzzzzzz",
                    "value": "4.587928"
                }
            ],
            "date_start": "2019-12-01",
            "date_stop": "2019-12-07"
        }
    ],
    "paging": {
        "cursors": {
            "before": "MAZDZD",
            "after": "MAZDZD"
        }
    }
}

Solution

  • import requests
    
    payload = {}
    
    headers = {
        'Authorization': 'Bearer <access_token>'
    }
    
    r = requests.get(
        "https://graph.facebook.com/v5.0/act_<------id------>/insights?fields=campaign_id,campaign_name,clicks,unique_clicks,reach,spend,impressions,cost_per_unique_click,purchase_roas,website_purchase_roas&time_range={\"since\":\"2019-12-01\",\"until\":\"2019-12-07\"}&time_increment(1)&limit(200)", headers=headers, json=payload).json()
    
    
    print(r)