Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse nested FB API response from Python SDK

I'm querying an Insights endpoint with the Facebook Python SDK and have a hard time making the response I get work with Python and, subsequently pandas. I do the following call:

   account = AdAccount('act_id')
    params = {
        'fields': [Insights.Field.impressions,Insights.Field.clicks,Insights.Field.actions,Insights.Field.spend],
        'breakdowns': [Insights.Breakdown.hourly_stats_aggregated_by_advertiser_time_zone],
         'time_range': {
            'since': 'start',
            'until': 'end',
        },
        'action_attribution_windows': ['7d_click'],
    }

    result = account.get_insights(params=params)
    print (result)

which returns data like so:

[<Insights> {
    "actions": [
        {
            "7d_click": 600,
            "action_type": "custom_event_xyz",
            "value": 50
        },
        {
            "7d_click": 600,
        ....
        }
    ],
    "clicks": 1500,
    "date_start": "start",
    "date_stop": "end",
    "hourly_stats_aggregated_by_advertiser_time_zone": "00:00:00 - 00:59:59",
    "impressions": "60000",
    "spend": 60
}, <Insights> {
              ....

]

While putting the data excluding the actionsdata into a pandas DataFrame, I do not manage to properly flatten the actions data so that the aggregation level is consistent (i.e. the "actions" keys as column headers). Having checked online and also on Stackoverflow, loading the json with python and processing it accordingly then as well as reading it with pandas are both options that do not work.

Summing up I don't see how I can elegantly mine the deeper nested parts of the response and easily make the contents compatible with the rest.

like image 251
thenaturalist Avatar asked Dec 04 '15 15:12

thenaturalist


People also ask

Does Facebook use REST API?

Yes, it is a REST API as well. Show activity on this post. Yes, there have been 3 Facebook API's to date: Legacy REST.

Is the Facebook API free?

In the newest version of the Graph API (v2. 9), we're announcing features that simplify development, making it even easier to build apps and experiences with Facebook. We're providing free access to over 140 million places around the world, the same data that powers Facebook, Instagram, and Messenger.


Video Answer


1 Answers

you just met the vary same problem as i did. The get_insights returns data is like json, but it is not. You can know what type it is just use type(result). It is facebookads.objects.EdgeIterator. You can change it's type by using result=[x for x in result],now the type of the 'result' is list!!! And then you can use pandas to do whatever you want, pandas.DataFrame(result).

like image 144
ye jiawei Avatar answered Sep 18 '22 20:09

ye jiawei