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! 😊

Tag:facebook, facebook-graph-api, facebook-graph-api-v2.0, facebook-insights

Add a new comment.