Posts under category Facebook Graph API

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

During development, the private reply API (https://graph.facebook.com/PAGE-ID/messages) was working correctly. However, after my app's review was rejected, the API started failing.

The error I encounter is:

"An unknown error has occurred."

Is it possible for an API to stop functioning after an app review rejection?

Investigated Details:
The token's validity has been confirmed as fine via the developer tools. The COMMENT-ID was obtained from the Webhook, so it should be correct. The PAGE-ID works with other APIs, so it also appears to be correct.

I'm building a webapp to help house hunters find the house. I was trying to read feeds of public Meta groups related to rentals.

From what I understand the group admin has to install my app and give me the access token. But I got to know that groups API is deprecated from v19.0.

Is there any official alternate or workaround that you guys know or are using in your own use case? Thanks.

From Facebook document: https://www.facebook.com/business/help/652738434773716 "You can have up to 5,000 ads. Only 1,000 of these 5,000 ads can use dynamic creative."

Some my adaccounts have an issue "Your account xxxx has reached the maximum number of dynamic creative ads allowed (1,000). Please delete some of your older ads."

How can I count ads that are using "dynamic creative"? Note: I can count ads by

        $adAccount = new AdAccount($adAccountId);         $cursor = $adAccount->getAds(             params: [                 'date_preset' => 'today',                 'summary' => 'total_count',                 'limit' => 1,             ]         ); 

It is great if I can find an API to get numbers ads use dynamic creative belong to each adaccount