Getting Ad Insights from Facebook — and avoiding error 17

Sam Kenny
Sam Kenny
Jan 14, 2016 · 1 min read

At untapt measuring the success of our marketing campaigns across social media is important — to us and our clients. If we are going to put dollars into a campaign to find the best tech talent around the world, we need to know which social media platforms are performing best.

I’ve struggled with the Facebook API so I thought I would do a quick recap of the solution I implemented in Python. In doing so, I had to make sure that the number of API calls was limited so avoid Error 17 — user request limit reached.

The most important discovery in the code below was that insights can be retrieved for the account, but to see them aggregated at the ad level you simply need to pass the ‘level’ parameter.

from facebookads.api import FacebookAdsApi
from facebookads.objects import AdAccount, AdCreative, AdPreview, AdCreativePreview, Ad, Insights
def get_facebook_insights():
FacebookAdsApi.init(FB_APP_ID, FB_APP_SECRET, FB_TOKEN)
account = AdAccount(FB_ACCT_ID)
account.remote_read(fields=[AdAccount.Field.timezone_name])
start = self.date.strftime('%Y-%m-%d')
end = self.date.strftime('%Y-%m-%d')
fields = [
Insights.Field.campaign_name,
Insights.Field.campaign_id,
Insights.Field.impressions,
Insights.Field.reach,
Insights.Field.actions,
Insights.Field.spend,
Insights.Field.ad_id
]
params = {
'time_range': {'since': start, 'until': end},
'level': 'ad',
'limit': 1000
}
insights = account.get_insights(fields=fields, params=params)
for i in insights:
people_reached = int(i['reach'])
impressions = int(i['impressions'])
spend = float(i['spend'])
Shout out to http://jakzaprogramowac.pl/pytanie/12122,fb-ads-api-17-user-request-limit-reached for pointing me in the right direction and also to this Stackoverflow response which was essential in helping me converting the access token I retrieved from the Facebook Graph Explorer to a long lived access token.

Sam Kenny’s a(musing)

Random tech articles and tidbits of interest

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store