Posts tagged with facebook-insights

Body:

I need to retrieve all daily metrics (e.g., impressions, reactions, video views) for my Facebook posts, videos, reels, etc., starting from their creation date. However, using Graph API v20.0 or higher, I only receive cumulative or incorrect data instead of individual daily values.

Here is what I’ve tried so far:

  1. Refreshing the Access Token:
    I've implemented token refresh logic to ensure a valid access token is always available.

  2. Fetching Metrics Daily:
    I request metrics using the insights endpoint with period=day. However, the results seem cumulative or incomplete.

Code Snippets:

1. Token Refresh Logic
The function below refreshes the token and saves it locally.

import requests from config import ACCESS_TOKEN, API_VERSION, CLIENT_ID, CLIENT_SECRET def refresh_access_token():     """Refresh the access token to get a new long-lived token."""     refresh_url = f"https://graph.facebook.com/{API_VERSION}/oauth/access_token"     params = {         'grant_type': 'fb_exchange_token',         'client_id': CLIENT_ID,         'client_secret': CLIENT_SECRET,         'fb_exchange_token': ACCESS_TOKEN,     }     response = requests.get(refresh_url, params=params)     if response.status_code == 200:         data = response.json()         new_access_token = data.get('access_token')         if new_access_token:             print("New token obtained:", new_access_token)             with open('access_token.txt', 'w') as token_file:                 token_file.write(new_access_token)             return new_access_token     else:         raise Exception(f"Error refreshing token: {response.status_code} - {response.text}") 

2. Fetch Daily Metrics for a Post
I fetch metrics using period=day, but the data is cumulative:

def fetch_daily_metrics(post_id, metrics, start_date, end_date):     token = get_access_token()     insights_url = f"https://graph.facebook.com/v20.0/{post_id}/insights"     params = {         'metric': ','.join(metrics),         'access_token': token,         'period': 'day',         'since': start_date,         'until': end_date,     }     response = requests.get(insights_url, params=params)     if response.status_code == 200:         return response.json().get('data', [])     else:         print(f"Error fetching metrics: {response.status_code}")         print(response.text)         return None 

3. Processing Metrics into Google Sheets
I use this to upload metrics into Google Sheets for analysis:

import pandas as pd from google_sheets import upload_to_google_sheets def process_and_upload_metrics(metrics_data):     rows = []     for metric in metrics_data:         name = metric['name']         for value in metric.get('values', []):             rows.append({'Date': value['end_time'], 'Metric': name, 'Value': value['value']})     df = pd.DataFrame(rows).pivot_table(index='Date', columns='Metric', values='Value').reset_index()     upload_to_google_sheets(df, "Facebook Insights", "Daily Metrics") 

Current Problems:

  1. Metrics are cumulative:
    I expected daily values but received cumulative ones. How can I ensure the API provides individual daily values?

  2. Data mismatch:
    Some metrics appear inconsistent with the Facebook UI insights.

  3. API Version:
    I’ve tested API versions from v15.0 to v21.0. Which version is recommended for daily metrics?

Any advice or suggestions would be greatly appreciated!


Tags:
[facebook-graph-api] [python] [google-sheets] [facebook-api]

Links:
Here’s the documentation I’ve been following.

Thank you for your help! 😊

I use facebook graph api in my app and I faced some issues I cannot crack for a while. Unfortunately their documentation is not always clear, so I would appreciate any tips on my questions. My app is build in Next.js, but I don't think language matters here.

1.Upload video trouble.

I follow this documentation. https://developers.facebook.com/docs/video-api/guides/publishing Publish video on the page takes three steps. 1.1 Start an upload session. I use here my business app Id and my test user account for user access token

 curl -i -X POST "https://graph.facebook.com/v20.0/<APP_ID>/uploads  ?file_name=<FILE_NAME>  &file_length=<FILE_LENGTH>  &file_type=<FILE_TYPE>  &access_token=<USER_ACCESS_TOKEN>" 

I get successfull return

{   "id": "upload:<UPLOAD_SESSION_ID>" } 

1.2. Start upload session. Same user token as in the first call and upload session Id which I received in the first response. Currently I test in Postman, so no issues yet converting video file, just file attached type video/mp4.

 curl -i -X POST "https://graph.facebook.com/v20.0/upload:<UPLOAD_SESSION_ID>"   --header "Authorization: OAuth <USER_ACCESS_TOKEN>"   --header "file_offset: 0"   --data-binary @<FILE_NAME> 

Success. Receive file handle response

{    "h": "2:c2FtcGxl..." } 

1.3. Publish video. And here is an error

 curl -X POST \   "https://graph-video.facebook.com/v20.0/<PAGE_ID>/videos" \   -F "access_token=<PAGE_ACCESS_TOKEN>" \   -F "title=<VIDEO_TITLE>" \   -F "description=<VIDEO_DESCRIPTION>" \    -F "fbuploader_video_file_chunk=<UPLOADED_FILE_HANDLE>" 

Page Id I use Page from my test user account, page token from this page. Handle - response from previous step. It end up in response:

{    "error": {       "message": "(#100) Using file handle created for another user",       "type": "OAuthException",       "code": 100,       "fbtrace_id": "AOF82skhP9OWC_yFlh_ka4q"    }  } 

Question? For whom did they create a handle?? Which another user? I use page credentials which belong to the user, whom user_token I used in the first steps. I follow all official documentation with headers, I insert user token in the header in the second step, as required, but I always end up with this error. Any ideas what potentially can go wrong?

2.Post Page insights for analytics.

I get analytics for page following this documentation https://developers.facebook.com/docs/graph-api/reference/v20.0/insights

For example call

  GET v20.0/{Page_Id}/insights?metric=page_post_engagements,page_daily_follows&period=week&since=01.09.2024&untill=30.09.2024 

There are three options for most of metrics - day, week and days_28. What is not clear for me, its's how to combine it with 'since' and 'untill'? I have an interactive page, where user can dynamically select 'period', 'since' and 'untill with datePicker, It always shows different data and I'm not sure what exactly I display.. for the call

 page_id/insights?metric=page_post_engagements&since=01.09.2024 

I will receive data for day, week, and day_28, per day since selected date till today. But data for the same day in each of there three sections will differ. What does this data represent? Example response:

 "name": "page_post_engagements",   "period": "day",   "values": [     {       "value": 0,       "end_time": "2024-09-02T07:00:00+0000"     },     {       "value": 0,       "end_time": "2024-09-03T07:00:00+0000"     },     {       "value": 0,       "end_time": "2024-09-04T07:00:00+0000"     },     {       "value": 0,       "end_time": "2024-09-05T07:00:00+0000"     },     {       "value": 9,       "end_time": "2024-09-06T07:00:00+0000"     },     {       "value": 4,       "end_time": "2024-09-07T07:00:00+0000"     }, }, {   "name": "page_post_engagements",   "period": "week",   "values": [     {       "value": 0,       "end_time": "2024-09-02T07:00:00+0000"     },     {       "value": 0,       "end_time": "2024-09-03T07:00:00+0000"     },     {       "value": 0,       "end_time": "2024-09-04T07:00:00+0000"     },     {       "value": 0,       "end_time": "2024-09-05T07:00:00+0000"     },     {       "value": 9,       "end_time": "2024-09-06T07:00:00+0000"     },     {       "value": 13,       "end_time": "2024-09-07T07:00:00+0000"     }, }, {   "name": "page_post_engagements",   "period": "days_28",   "values": [     {       "value": 5,       "end_time": "2024-09-02T07:00:00+0000"     },     {       "value": 5,       "end_time": "2024-09-03T07:00:00+0000"     },     {       "value": 5,       "end_time": "2024-09-04T07:00:00+0000"     },     {       "value": 5,       "end_time": "2024-09-05T07:00:00+0000"     },     {       "value": 14,       "end_time": "2024-09-06T07:00:00+0000"     },     {       "value": 18,       "end_time": "2024-09-07T07:00:00+0000"     }, 

Can someone explain me please? If I want, for example, display : "Your page activity this week increased/dropped for 15% compare to last week", how do I need to set my search params?

Thanks everyone for any ideas

I'm trying to fetch insights for my ad sets using the Facebook Graph API. Here are the parameters and the request I'm making:

params_insights_get = {     "access_token": "ACCESS_TOKEN",     "level": "adset",     "fields": "reach,impressions,estimated_ad_recall_rate,frequency,full_view_impressions,full_view_reach,clicks,inline_link_clicks,outbound_clicks,video_play_retention_0_to_15s_actions,video_play_retention_20_to_60s_actions,actions,spend,instagram_upcoming_event_reminders_set,inline_link_click_ctr,outbound_clicks_ctr,unique_inline_link_clicks,cost_per_ad_click,cost_per_conversion,cost_per_one_thousand_ad_impression,cost_per_outbound_click,cost_per_thruplay,cost_per_unique_action_type,cost_per_unique_click,cost_per_unique_inline_link_click,cost_per_unique_outbound_click,cost_per_action_type,cpc,cpm,cpp,ctr,optimization_goal,adset_id,adset_name", } root_url = f"https://graph.facebook.com/v19.0/" campaigns_ext = "/campaigns" adsets_ext = "/adsets" insights_ext = "/insights" response_insights_get = requests.get(     root_url + campaign_id + insights_ext, params=params_insights_get ) 

This was working fine for the last six months. However, recently, I keep getting the following error response:

{     "error": {         "message": "Service temporarily unavailable",         "type": "OAuthException",         "is_transient": False,         "code": 2,         "error_subcode": 1504018,         "error_user_title": "Your request timed out",         "error_user_msg": "Please try a smaller date range, fetch less data, or use async jobs",         "fbtrace_id": "AvoEH7ogR7jlllCmCC943cH",     } } 

The date range I need is 7 days, i.e. the default value, and I need all the data in the query. I've tried async jobs, but the jobs keep failing. Interestingly, this only affects one particular campaign in my sample adaccount, the others work fine.

I'm currently working on an automated system that gathers Instagram profile insight data and sends it to an endpoint. However, I'm facing a challenge due to the large number of Instagram accounts I need to manage—more than 100 in total.

As a beginner in this area, I understand that utilizing the Instagram Graph API would be the most efficient approach. However, manually setting up access for each of the accounts seems like a time-consuming task.

Could anyone provide guidance on how to streamline this process? I'm looking for a clear explanation or a step-by-step guide on how to automate access to the Instagram Graph API for multiple accounts.

Any help or insights would be greatly appreciated!

Response example not showing conversions:

I'm trying to retrieve some ads insights so I can use them in my custom dashboard, everything is good but anything is related to conversions(results) is not returning in response. I gave all permissions to the access token and still no results.

What's the problem and how can I get this conversions/leads/results?

this is the required permissions for reading ads: read_insights, ads_management, ads_read, business_management, leads_retrieval. all of them included in the access token.