Skip to content

Facebook Page Insights to PostgreSQL: A Script You Own

Want your Facebook Page numbers in your own database? One short Python script, the tables, the queries, and the same for TikTok Ads and LinkedIn Ads spend.

Florian Darroman

Co-founder of Pozy · Updated 18 Nov 2026 · 18 min read

TL;DR

Pozy has no built-in PostgreSQL sync. A 143-line Python script does the job: it reads your Facebook Page's daily numbers from Pozy and writes them to your own database. Run it once a day. The same script copies TikTok Ads and LinkedIn Ads spend.

Try Pozy free for 7 daysCard required, cancel anytime.

After this article, you'll be able to:

  • Copy your Facebook Page's daily views, engagements and followers into your own PostgreSQL database
  • Load a full year of history on the first run, then only the last 7 days
  • Keep every post's views, comments and clicks in a second table
  • Add TikTok Ads and LinkedIn Ads spend to the same database
  • Know the limits before you build: 89 days a request, a one-day shift in the dates, old metric names that no longer work

Our Distribb Facebook Page went from 1,576 followers to 3,028 in 11 days.

I wanted those numbers in our own database, next to everything else. Not in a dashboard I have to open.

So I ran one script against the Page. In 10 seconds it filled 2,210 rows of daily numbers, a full year, and copied 126 posts.

2,210

rows of daily Page numbers, a year back

126

posts copied with their views, comments and clicks

10 seconds

the first run. The daily run takes under 3

One run of the script below on the Distribb Facebook Page, on the morning of 18 Nov 2026 (Bali time), into PostgreSQL 18 on my Mac. The follower counts are the rows dated 6 Nov and 17 Nov 2026.

Let me show you exactly how it works.

#Some context

Pozy connects to your Facebook Page once. After that, one key reads its numbers through Pozy's social media API.

Pozy does not write to your database for you. I co-founded Pozy, so I'd rather say that up front.

What it gives you is one clean answer a day: views, engagements, followers. The script takes that answer and writes it to PostgreSQL.

You own the script. You own the tables.

  1. Your Facebook Page
  2. Pozy reads its numbers
  3. The script asks Pozy once a day
  4. Rows in your PostgreSQL

You need three things: a Pozy account, Python 3.9 or newer, and a PostgreSQL database. Mine runs on my Mac. A hosted one works the same way, as long as it accepts connections from the machine that runs the script.

#Step 1: Connect your Facebook Page to Pozy

Open Connections, then Accounts, and choose New connection. Pick your project, then Facebook. Sign in on Facebook's own screen and approve.

Pozy never asks for your Facebook password. The full walkthrough is in how to connect your accounts.

You need a role on the Page that lets you see its insights. Once the account shows as Connected, Pozy can read its numbers.

#Step 2: Create a key that can only read

The script proves who it is with a key. Make one that can read and nothing else. If it ever leaks, nobody can post with it.

Open the keys page in the dashboard and click Create key.

Setting What I picked Why
Name postgres-sync So I know what it's for in six months
Expires Never A key that expires stops your daily run without telling you
Profiles All profiles Pick Specific profiles to limit the key to one project
Permission Read only The script never posts. It only looks

Copy the key right away. Pozy shows it once and keeps no copy. It starts with pz_live_.

Workspace owners and admins can create keys.

#Step 3: Find the id of your Page in Pozy

Each connected account has an id. The script needs the one of your Page.

Save the key in your terminal first, then ask Pozy for your Facebook accounts.

Text
export POZY_API_KEY="pz_live_..."

curl "https://api.pozy.ai/v1/accounts?platform=facebook" \
  -H "Authorization: Bearer $POZY_API_KEY"

# the answer, trimmed to the lines you need
{ "accounts": [
    { "_id": "6af075bc...", "platform": "facebook", "username": "distribb", "displayName": "Distribb" }
] }

The _id is what you want. Keep it for the next step.

#Step 4: Ask for three days and read the answer

Before you build anything, look at what comes back. I asked for our Page's views from 14 to 16 November, one number a day.

Text
curl "https://api.pozy.ai/v1/analytics/facebook/page-insights?accountId=YOUR_PAGE_ID&metricType=time_series&metrics=page_media_view,page_follows&fromDate=2026-11-14&toDate=2026-11-16" \
  -H "Authorization: Bearer $POZY_API_KEY"

# the answer for the Distribb Page, 18 Nov 2026 (trimmed)
{ "platform": "facebook",
  "dateRange": { "since": "2026-11-14", "until": "2026-11-16" },
  "metrics": {
    "page_media_view": { "total": 100392, "values": [
      { "date": "2026-11-15", "value": 21572 },
      { "date": "2026-11-16", "value": 50667 },
      { "date": "2026-11-17", "value": 28153 } ] },
    "page_follows": { "total": 3028, "values": [
      { "date": "2026-11-15", "value": 2731 },
      { "date": "2026-11-16", "value": 2930 },
      { "date": "2026-11-17", "value": 3028 } ] } },
  "dataDelay": "Meta page insights may be delayed up to 24 hours. ..." }

Each metric is a list of days: one database row each.

And look at the dates. I asked for the 14th to the 16th. The rows say the 15th to the 17th. I come back to that below.

These are the metrics you can ask for.

Metric What it counts
page_media_view Views of your Page's content
page_total_media_view_unique People who saw it
page_views_total Visits to the Page itself
page_post_engagements Reactions, comments, shares and clicks on your posts
page_video_views, page_video_view_time Video views and time watched
page_follows Followers on that day (a running total, never add it up)
followers_gained, followers_lost New and lost followers a day, from Pozy's own daily count
page_actions_post_reactions_like_total and five more One count per reaction: like, love, wow, haha, sorry, anger
content_monetization_earnings, monetization_approximate_earnings What a monetized Page earned

The old names are gone. On 15 November 2025, Meta retired page_impressions, page_fans, page_fan_adds and page_fan_removes, with their variants. Meta's own list is on its deprecated metrics page.

Retired name Use now
page_impressions page_media_view
page_fans page_follows
page_fan_adds, page_fan_removes Meta lists no replacement. Pozy's followers_gained and followers_lost fill the gap

Ask Pozy for a retired name and it refuses with the list of valid ones. The full reference is on Pozy's platform insights page.

#Step 5: Decide what the tables look like

I use three tables. The script creates them on its first run.

Table One row is Columns
facebook_page_daily One metric, on one day, for one Page account_id, day, metric, value, synced_at
facebook_posts One post post_id, account_id, url, published_at, caption, impressions, reach, views, likes, comments, shares, clicks, synced_at
ads_daily One day of spend, per ads connection and currency account_id, day, currency, spend, impressions, clicks, conversions, purchase_value, synced_at

The first table is tall on purpose: one row per metric, not one column per metric.

Meta renames and retires metrics. With a column per metric, every change means changing the table. With a row per metric, a new metric is just new rows.

Each table has a key that makes a row unique. For the daily table it's the Page, the day and the metric. For posts it's the post. For ads it's the connection, the day and the currency. So the script can run twice without writing a duplicate. It updates the row instead. PostgreSQL calls that ON CONFLICT DO UPDATE.

#Step 6: Run the script

Here is the whole thing. Save it as sync.py in a new folder, or download sync.py.

Python
"""Copy Facebook Page insights from Pozy into PostgreSQL. Run it once a day."""
import os
import time
from datetime import date, timedelta

import psycopg
import requests

API = "https://api.pozy.ai/v1"
KEY = os.environ["POZY_API_KEY"]            # a read-only Pozy key
PAGES = [p.strip() for p in os.environ["POZY_FACEBOOK_ACCOUNTS"].split(",") if p.strip()]
ADS = [a.strip() for a in os.environ.get("POZY_ADS_ACCOUNTS", "").split(",") if a.strip()]  # optional
DB = os.environ["DATABASE_URL"]             # postgresql://user:password@host:5432/dbname
DAYS_BACK = int(os.environ.get("DAYS_BACK", "7"))
METRICS = ("page_media_view,page_total_media_view_unique,page_views_total,"
           "page_post_engagements,page_video_views,page_follows,"
           "followers_gained,followers_lost")

TABLES = """
create table if not exists facebook_page_daily (
  account_id text not null,
  day        date not null,
  metric     text not null,
  value      numeric not null,
  synced_at  timestamptz not null default now(),
  primary key (account_id, day, metric)
);
create table if not exists facebook_posts (
  post_id      text primary key,
  account_id   text not null,
  url          text,
  published_at timestamptz,
  caption      text,
  impressions  bigint, reach bigint, views bigint, likes bigint,
  comments     bigint, shares bigint, clicks bigint,
  synced_at    timestamptz not null default now()
);
create table if not exists ads_daily (
  account_id  text not null,
  day         date not null,
  currency    text not null,
  spend       numeric, impressions bigint, clicks bigint,
  conversions numeric, purchase_value numeric,
  synced_at   timestamptz not null default now(),
  primary key (account_id, day, currency)
);
"""


def get(path, **params):
    """One read from Pozy. Waits and retries when Pozy says slow down."""
    while True:
        r = requests.get(API + path, params=params, timeout=60,
                         headers={"Authorization": f"Bearer {KEY}"})
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "5")))
            continue
        r.raise_for_status()
        return r.json()


def windows(start, end, size=88):
    """Pozy answers 89 days of page insights at a time, so cut long ranges up."""
    while start <= end:
        stop = min(start + timedelta(days=size), end)
        yield start, stop
        start = stop + timedelta(days=1)


def sync_page(db, page_id, start, end):
    rows = 0
    for a, b in windows(start, end):
        data = get("/analytics/facebook/page-insights", accountId=page_id,
                   metricType="time_series", metrics=METRICS,
                   fromDate=a, toDate=b)
        for metric, series in data["metrics"].items():
            for point in series.get("values", []):
                if point.get("value") is None:
                    continue
                db.execute(
                    """insert into facebook_page_daily (account_id, day, metric, value)
                       values (%s, %s, %s, %s)
                       on conflict (account_id, day, metric)
                       do update set value = excluded.value, synced_at = now()""",
                    (page_id, point["date"], metric, point["value"]))
                rows += 1
    return rows


def sync_posts(db, page_id, start, end):
    rows, page = 0, 1
    while True:
        data = get("/analytics", accountId=page_id, platform="facebook",
                   fromDate=start, toDate=end, limit=100, page=page)
        for post in data["posts"]:
            n = post.get("analytics") or {}
            db.execute(
                """insert into facebook_posts (post_id, account_id, url, published_at, caption,
                     impressions, reach, views, likes, comments, shares, clicks)
                   values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                   on conflict (post_id) do update set
                     impressions = excluded.impressions, reach = excluded.reach,
                     views = excluded.views, likes = excluded.likes,
                     comments = excluded.comments, shares = excluded.shares,
                     clicks = excluded.clicks, synced_at = now()""",
                (post["_id"], page_id, post.get("platformPostUrl"), post.get("publishedAt"),
                 post.get("content"), n.get("impressions"), n.get("reach"), n.get("views"),
                 n.get("likes"), n.get("comments"), n.get("shares"), n.get("clicks")))
            rows += 1
        if page >= data["pagination"]["pages"]:
            return rows
        page += 1


def sync_ads(db, account, start, end):
    data = get("/ads/timeline", accountId=account, fromDate=start, toDate=end)
    for row in data["rows"]:
        db.execute(
            """insert into ads_daily (account_id, day, currency, spend, impressions,
                 clicks, conversions, purchase_value)
               values (%s, %s, %s, %s, %s, %s, %s, %s)
               on conflict (account_id, day, currency) do update set
                 spend = excluded.spend, impressions = excluded.impressions,
                 clicks = excluded.clicks, conversions = excluded.conversions,
                 purchase_value = excluded.purchase_value, synced_at = now()""",
            (account, row["date"], row.get("currency") or "", row.get("spend"),
             row.get("impressions"), row.get("clicks"), row.get("conversions"),
             row.get("purchaseValue")))
    return len(data["rows"])


if __name__ == "__main__":
    end = date.today()
    start = end - timedelta(days=DAYS_BACK)
    # a post keeps collecting views for weeks, so posts are read at least 90 days back
    posts_start = end - timedelta(days=max(DAYS_BACK, 90))
    with psycopg.connect(DB, autocommit=True) as db:
        db.execute(TABLES)
        for page_id in PAGES:
            print("page rows:", sync_page(db, page_id, start, end))
            print("post rows:", sync_posts(db, page_id, posts_start, end))
        for account in ADS:
            print("ads rows:", sync_ads(db, account, start, end))

Create the database if you don't have one yet. Then, in the folder with sync.py, put your three values in a file called env.sh.

Text
createdb marketing
Text
# env.sh
export POZY_API_KEY="pz_live_..."
export POZY_FACEBOOK_ACCOUNTS="the _id from step 3"
export DATABASE_URL="postgresql://user:password@host:5432/marketing"
# on your own machine: postgresql://localhost/marketing

That file holds your key and your database password. Make it readable by you alone, install the two libraries the script needs, and run it with a year of history.

Text
chmod 600 env.sh
python3 -m venv venv
./venv/bin/pip install requests "psycopg[binary]"

. ./env.sh
DAYS_BACK=365 ./venv/bin/python sync.py

# what I got on the Distribb Page, 18 Nov 2026
page rows: 2210
post rows: 126

That took 10 seconds. A year is longer than Pozy answers in one go, so the script cut it into five requests.

Two Pages? Put both ids in POZY_FACEBOOK_ACCOUNTS, with a comma between them. Want another metric from the table in step 4? Add its name to the METRICS line. I ran the eight that are there.

#Step 7: Check the rows with a query

This query turns the tall table back into one line a day.

Text
select day,
       max(value) filter (where metric = 'page_media_view')       as views,
       max(value) filter (where metric = 'page_post_engagements') as engagements,
       max(value) filter (where metric = 'page_follows')          as followers
from facebook_page_daily
where day between date '2026-11-06' and date '2026-11-17'
group by day order by day;

day        | views | engagements | followers
-----------+-------+-------------+----------
2026-11-06 | 69    | 3           | 1576
2026-11-07 | 3888  | 92          | 1595
2026-11-08 | 48745 | 1134        | 1853
2026-11-09 | 29707 | 660         | 1991
2026-11-10 | 23096 | 560         | 2093
2026-11-11 | 45123 | 951         | 2305
2026-11-12 | 21091 | 447         | 2383
2026-11-13 | 56725 | 916         | 2595
2026-11-14 | 18206 | 432         | 2648
2026-11-15 | 21572 | 565         | 2731
2026-11-16 | 50667 | 1129        | 2930
2026-11-17 | 28153 | 647         | 3028
(12 rows)

69 views one day, 48,745 two days later. That's the week the Page woke up.

A bar chart of daily views on the Distribb Facebook Page from 19 October to 17 November 2026, low until 7 November then between 18,000 and 57,000 a day
Views a day on the Distribb Facebook Page, drawn from the facebook_page_daily table. Rows dated 19 Oct to 17 Nov 2026: 363,137 views in total, 56,725 on the best day. Read 18 Nov 2026.

The posts table answers the next question: which posts did that?

Text
select left(caption, 40) as post,
       (published_at at time zone 'UTC')::date as posted,
       views, comments, clicks
from facebook_posts order by views desc nulls last limit 5;

post                                     | posted     | views | comments | clicks
-----------------------------------------+------------+-------+----------+-------
ChatGPT Plugin to automate SEO backlinks | 2026-09-03 | 61385 | 401      | 548
Claude Connector to Automate SEO backlin | 2026-08-25 | 59026 | 289      | 587
                                         | 2026-10-13 | 58139 | 302      | 617
Turn Claude into an SEO machine with 21  | 2026-11-15 | 53936 | 335      | 503
Claude Fable 5.2 is out. Connect it to y | 2026-11-11 | 53777 | 186      | 432
(5 rows)

The third post is a Reel with no caption, so that cell is empty.

And a month by month view takes four lines.

Text
select to_char(date_trunc('month', day), 'YYYY-MM') as month, sum(value) as views
from facebook_page_daily
where metric = 'page_media_view' and day between date '2026-06-01' and date '2026-10-31'
group by 1 order by 1;

month   | views
--------+-------
2026-06 | 28129
2026-07 | 24066
2026-08 | 59310
2026-09 | 101951
2026-10 | 91056
(5 rows)

#Step 8: Run it every day

Without DAYS_BACK, the script reads the last 7 days of Page numbers and the last 90 days of posts. On our Page that's 60 rows and 25 posts in under 3 seconds.

Why 7 days and not 1? Meta's numbers can arrive up to 24 hours late. Reading the week again corrects the rows that moved.

Why 90 days of posts? A post keeps collecting views long after it goes out. A post older than 90 days keeps the numbers of its last read.

On a Mac or a Linux server, one line in crontab -e runs it every morning at 6.

Text
0 6 * * * cd /path/to/pozy-sync && . ./env.sh && ./venv/bin/python sync.py >> sync.log 2>&1

A laptop that's asleep at 6 skips the run, so a server is the better home. Each run adds its row counts to sync.log. If a run fails, the error is the last thing in that file. Look at it the first few mornings.

No server? The same script runs on a schedule in GitHub Actions, or any tool that can run Python once a day.

One daily run is 2 requests for the Page and its posts. Pozy allows 120 a minute on the Standard to Ultimate plans, so you won't get near the limit.

#Step 9: Add your TikTok Ads and LinkedIn Ads spend

The script already has the part for ads. It stays off until you give it an ads connection.

Connect the ad network in Pozy first: Ads, then Overview, then Connect an ad account (the guide). An ads connection gets its own id, like your Page did. Find it the same way as in step 3, without the platform filter. Its platform reads tiktokads or linkedinads.

Text
# add this line to env.sh, then run the script again
export POZY_ADS_ACCOUNTS="your TikTok Ads id,your LinkedIn Ads id"

It writes one row per day, per connection and per currency into ads_daily.

I have to be straight here. We run no ads from our Pozy account. So I ran the Facebook part on real data, and the ads part only on a sample row shaped like Pozy's docs. Check your first rows against your ads manager.

What you get depends on the network. This is from Pozy's ads reporting docs.

Network What lands in ads_daily
TikTok Ads Spend, impressions, clicks and conversions
LinkedIn Ads Spend, impressions and clicks. Conversions come per conversion rule
Meta Ads All of it, with purchase value
Google Ads Spend, impressions, clicks and conversions
Pinterest, X, Reddit, ChatGPT Ads Spend, impressions and clicks only

Three rules from the same docs:

  • When you connect an ad account, Pozy imports its last 90 days. Older days are not there, except on Meta. Ask Meta for older days and Pozy sends what it has while it imports the rest, so run the script again later.
  • Pozy never converts currencies. That's why currency is part of the key. Never add dollars and euros.
  • Days follow the ad account's time zone, not yours.

#What went wrong before it worked

The dates are one day ahead. I asked for 16 November alone. I got one row, dated 17 November. It looks like each row is stamped with the end of its day. So in your queries, read the row dated the 17th as the 16th. followers_gained and followers_lost did not shift in my test. The script stores every date as Pozy sends it, so the month totals in step 7 use the stamped dates.

A long range in one request fails. I asked for 108 days. Pozy answered: "Date range cannot exceed 89 days". The windows function cuts the range into pieces of 89 days.

New followers only go back a week. followers_gained and followers_lost come from a count Pozy takes every day. On our Page they start on 10 November 2026. The total, page_follows, goes back the full year. A day can be missing too: ours has no row for 15 November.

The follower total moves. I ran the script several times in 20 minutes. Past days' page_follows went up by 1 or 2 between runs, and not all by the same amount. So reload the whole range in one run before you compare two dates.

The last rows are not final. When I ran it, the newest row read 0 and the one before was still filling up. Don't report on the last two rows.

Old metric names fail loudly. A script written for page_impressions breaks today. A silent zero would be worse.

Meta keeps two years, and small Pages get nothing. Meta's Page Insights reference says only the last two years are available, and only for Pages with 100 likes or more. Start your copy now. What you don't store, you lose.

#Should you write a script or pay for a connector?

There are paid tools that copy Facebook numbers into PostgreSQL with no code. Here's how I'd decide:

Your own script on Pozy A ready-made data connector
Setup You need somewhere to run Python once a day A few clicks
When Meta changes a metric You change one line, the list of metrics. The tall table stays as it is The vendor updates it
Table design Yours Theirs
Other sources (CRM, payments, other apps) Only what Pozy connects Their whole catalog
What else the money buys Posting, the inbox, comment-to-DM, ads and your AI on the same accounts Data copying only

Pick a connector if you need many sources in one database and nobody on the team writes Python.

Pick the script if you already use Pozy, or you want your social numbers and your posting in one place.

For your website's traffic, you may not need a script at all. With GA4 connected to Pozy, Claude can audit your Google Analytics from one line.

Your turn

#How to do this with Pozy

You don't have to type the script yourself. Claude can set it up, and Pozy gives it the numbers.

  1. Connect your Facebook Page to Pozy, like in step 1.
  2. Create a read-only key in the dashboard, like in step 2.
  3. Add Pozy to Claude. It's one link: add Pozy to Claude.
  4. Send the prompts below. The first one is for Claude Code, on the computer where the script will run.
Prompt for Claude or ChatGPT

Download https://pozy.ai/blog/facebook-page-insights-to-postgresql/sync.py into a new folder. Install what it needs. My Pozy key is in the POZY_API_KEY variable and my database address is in DATABASE_URL. Find the id of my Facebook Page with the key, put it in POZY_FACEBOOK_ACCOUNTS, run the script once with DAYS_BACK=365, then show me the row count per metric. Do not print my key.

Prompt for Claude or ChatGPT

Set the script up to run every morning at 6 on this machine. Keep my key and database password in a file only I can read. Then show me how to check tomorrow that it ran.

Prompt for Claude or ChatGPT

Look at the facebook_page_daily and facebook_posts tables in my database. Write me three queries: views and engagements per week, the 10 posts with the most views, and the days I gained the most followers. Remember that each daily row is dated one day after the day it measures, except followers_gained and followers_lost.

Prompt for Claude or ChatGPT

Use Pozy for this. Read my Facebook Page's numbers for the last 28 days and my 5 best posts. Tell me what the best posts have in common, then draft 3 new posts like them. Show me the drafts before you schedule anything. If you cannot see Pozy's tools yet, tell me how to connect Pozy first.

Start your 7-day free trialTry every feature free for 7 days.

#Questions

Does Pozy sync Facebook Page Insights to PostgreSQL by itself?

No. Pozy reads the numbers and gives them to you through one key. The script above writes them to your database. Pozy's dashboard can also export a spreadsheet file by hand, from Analytics. Nothing in Pozy writes to a database for you.

Is Facebook Insights still available?

Yes. Meta still shows Insights in its own tools. What changed is the metric names. On 15 November 2025, Meta retired the old ones, like page_impressions and page_fans. The current ones are in the table in step 4.

How do I export data from Facebook Insights?

Two ways. By hand, from Meta's own tools. Or through Meta's API, which is what Pozy reads for you. The script above is the second way, on repeat, with no file to download.

How do I get Facebook Page insights without the script?

Ask for them once, like in step 4. Or ask Claude through Pozy, with the last prompt above.

How far back can I load?

On our Page I loaded 365 days in one run, 89 days a request. Meta itself keeps the last two years. The daily new and lost followers only start on the day Pozy begins counting them.

Will running it twice create duplicates?

No. Each row has a key: the Page, the day and the metric. A second run updates the row. On our Page the table held 2,210 rows after the first run and after the second.

How often should it run?

Once a day is enough. Meta's reference says most Page metrics update once every 24 hours. An hourly run would mostly read the same numbers again.

Does it work with Supabase, Neon or Amazon RDS?

It should: they are all PostgreSQL. Put their direct connection address in DATABASE_URL, not a pooled one. I only ran it on PostgreSQL 18 on my Mac. Expect a slower first run on a remote database: the script writes one row at a time.

Can I add Instagram, YouTube or LinkedIn the same way?

Yes, with one more function each. Pozy reads account numbers for Instagram, YouTube, LinkedIn pages, TikTok and Google Business too. Each has its own metric names and limits. Of Instagram's account insights, for example, only reach comes day by day. They're listed on the platform insights page linked in step 4. Add a platform column to the tall table first.

What does it cost?

Pozy starts at $29 a month, or $23 a month billed yearly, for 5 connected accounts. Each plan includes the API and starts with a 7-day free trial. PostgreSQL and Python are free.

Do I need a database at all?

Not to read your numbers. Pozy's analytics shows them, and Claude or ChatGPT can read them through Pozy. A database earns its place when you join them with your own data: sales, sign-ups, support tickets.