> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# How do I compare engagement changes between two observations of an Instagram campaign post?

> Save two observations of the same post or Reel, compare net changes and retain actual observation times, missing values and sources.

To measure how engagement on an Instagram campaign post changed, save two responses from the same detail action, `instagram.v2.fetch_post_info` or `instagram.v3.get_post_info`. Check that both responses describe the same shortcode and account, export each response to a CSV with `instagram_snapshot.py`, and calculate the changes locally with `compare_instagram.py`. If you have only one response, keep the response as the baseline for the next observation.

For example, for a launch Reel, record likes, comments and plays on launch day and check again the next day. Give the team both observation times, the counts, the net changes and the sources.

## Which question are you answering?

| Question                                   | Observation method                                                                               |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| How did this item's counters change?       | Compare the same shortcode and detail action at two explicit times                               |
| Which campaign posts deserve closer study? | Retain publication times and observe at comparable post ages before reviewing content            |
| Why did engagement change?                 | Investigate campaign timing, content and other evidence; the snapshots show only counter changes |

Deliver two snapshots, the original responses and a change report with the before and after values, net changes, elapsed time and availability of each counter. A photo without play data can still be compared by likes and comments.

## How do I brief an assistant?

> Save this campaign Reel's current engagement with shortcode, caption, account and query time. Once another observation of the same item is available, compare net changes in likes, comments and plays with both sources. List unavailable values and state the observation interval.

`instagram_snapshot.py` saves one post, and `compare_instagram.py` compares two saved observations. You schedule the later retrieval yourself; neither script installs a scheduler. Each detail request is charged at the current [pricing](https://beatapi.io/pricing); the local comparison needs no additional detail request.

## 1. Prepare the target and budget

Prepare the post link and its shortcode for `data:instagram.v2.fetch_post_info`. Save the first observation now, and use the same detail action for the later observation so the two records are comparable. If you already have a valid response, start at step 3.

## 2. Retrieve and save the detail

```bash
mkdir instagram-query-1 && \
curl --fail-with-body -sS https://api.beatapi.io/v1/social-data/call \
  -H "Authorization: Bearer $BEATAPI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"action":"instagram.v2.fetch_post_info","params":{"code_or_url":"<post_url_or_shortcode>"}}' \
  -D instagram-query-1/response.headers \
  -o instagram-query-1/response.json
```

Replace `<post_url_or_shortcode>` with your post. On an HTTP failure, keep the error output and stop. After an HTTP success, still check the business `status` in `response.json`. Keep the raw JSON and the `request_id` for traceability.

## 3. Export the requested post

Save the script below as `instagram_snapshot.py` and run it with Python 3. The input is the direct `/v1/social-data/call` response. The script reads `action` to choose v2 `data.data` or v3 `data.items[]`, then requires exactly one item whose `code` matches. The script keeps zero and missing values distinct, escapes text that starts with a formula character and refuses to overwrite an existing CSV.

```python
import csv, hashlib, json, pathlib, re, sys
from decimal import Decimal, InvalidOperation
source, destination, expected_code = sys.argv[1:4]
source_path = pathlib.Path(source).resolve()
raw = source_path.read_bytes()
r = json.loads(raw)
if r.get("status") != "succeeded" or r.get("error") is not None:
    raise ValueError("Call did not succeed")
if not isinstance(r.get("request_id"), str) or not r["request_id"].strip():
    raise ValueError("Missing request ID; cannot preserve query evidence")
action = r.get("action")
if action == "instagram.v2.fetch_post_info":
    candidates = [r["data"]["data"]]
elif action == "instagram.v3.get_post_info":
    candidates = r["data"]["items"]
else:
    raise ValueError("Unsupported detail action")
matches = [x for x in candidates if isinstance(x, dict) and x.get("code") == expected_code]
if len(matches) != 1:
    raise ValueError("Expected exactly one matching shortcode")
p = matches[0]
identity = p.get("id")
if identity is not None and not ((isinstance(identity, str) and identity.strip()) or (type(identity) is int and 0 <= identity <= 9007199254740991)):
    raise ValueError("Post ID must be an original nonempty string or safe integer")
metrics = p.get("metrics") if action == "instagram.v2.fetch_post_info" else p
if not isinstance(metrics, dict):
    raise ValueError("Missing metric object")
def count(value):
    if value is None:
        return None
    if type(value) is int and 0 <= value <= 9007199254740991:
        return value
    if isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
        return int(value)
    raise ValueError("Use a safe nonnegative integer or original ASCII digit string; do not guess a rounded metric")
def scalar(value):
    if value is None: return ""
    text = str(value)
    return "'" + text if text.lstrip().startswith(("=", "+", "-", "@")) else text
row = [p.get("id"), p["code"], (p.get("caption") or {}).get("text"),
       (p.get("user") or {}).get("username"), p.get("taken_at"),
       count(metrics.get("like_count")), count(metrics.get("comment_count")), count(metrics.get("play_count")),
       p.get("product_type"), r.get("request_id"), action, str(source_path), hashlib.sha256(raw).hexdigest()]
with pathlib.Path(destination).open("x", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["id","code","caption","username","taken_at","likes","comments","plays",
                     "product_type","request_id","action","source_file","source_sha256"])
    writer.writerow([scalar(x) for x in row])
print(json.dumps({"rows":1,"code":p["code"],"action":action}))
```

## 4. Run and check the result

```bash
python3 instagram_snapshot.py instagram-query-1/response.json instagram-snapshot-1.csv YOUR_SHORTCODE
```

Check `code` and `username` against your source URL; `rows` should be 1. v2 counters come from the `metrics` object; v3 counters sit on the item itself. `caption` is the post text, not a transcript. `taken_at` is the publication time, not the collection time, so record the collection time separately in your collection manifest. If the export fails, read the error instead of producing a zero-engagement row.

## 5. Collect the second snapshot without overwriting the first

For the next query, use a new filename and record the collection time. Compare likes, comments and plays only between valid snapshots of the same `code`, and leave missing counters out of the differences. Plays are not unique reach, and a difference is not follower growth. Keep both raw responses before comparing, and never overwrite an earlier snapshot.

[Detail inputs](/faq/instagram-url-and-id) · [Metric paths](/faq/instagram-metric-paths) · [Similar accounts](/faq/instagram-similar-accounts)

Sources: the gateway output contracts for `data:instagram.v2.fetch_post_info` and `data:instagram.v3.get_post_info` and the current response rendering.

## 6. Answer “How much did this Reel change after the first snapshot?”

`compare_instagram.py` compares two saved CSV snapshots locally, without another request. Both snapshots must come from the same shortcode and the same detail action. Pass the actual API query times, not file modification times. Missing plays on a photo stay missing, and a zero baseline does not produce an infinite growth rate. `compare_instagram.py` reports net changes, including downward revisions; the net changes are not new followers, unique reach or attributed campaign impact.

Save the script below as `compare_instagram.py` and run `python3 compare_instagram.py instagram-snapshot-1.csv 2026-11-16T10:00:00Z instagram-snapshot-2.csv 2026-11-17T10:00:00Z instagram-change.json`, replacing the example times with your query times. `instagram-change.json` contains both sources, both request IDs, the elapsed observation time and the before, after and change values for each counter. Different targets, reversed times, invalid counts or an existing output file stop the script. To compare different posts, collect each post at the same age after publication instead of ranking current totals.

```python
import csv
import re
import hashlib
import json
import sys
from datetime import datetime
from decimal import Decimal, InvalidOperation
from pathlib import Path

before_file, before_time, after_file, after_time, output = sys.argv[1:]
def load(filename):
    with Path(filename).open(encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle)
        expected = {"id", "code", "caption", "username", "taken_at", "likes", "comments", "plays", "product_type", "request_id", "action", "source_file", "source_sha256"}
        if not expected.issubset(set(reader.fieldnames or [])):
            raise SystemExit("Use complete snapshot headers, including empty metric columns")
        rows = list(reader)
    if len(rows) != 1 or not rows[0].get("code"):
        raise SystemExit("Expected exactly one snapshot row with a shortcode")
    return rows[0]
def stamp(value):
    result = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if result.utcoffset() is None:
        raise SystemExit("Use an actual query time with timezone")
    return result
def verify_source(row):
    source = Path(row["source_file"])
    if not source.is_absolute():
        raise SystemExit("Re-export snapshots with an absolute raw-response path")
    raw = source.read_bytes()
    digest = hashlib.sha256(raw).hexdigest()
    if digest != row["source_sha256"]:
        raise SystemExit("Raw response changed; do not compare this snapshot")
    response = json.loads(raw)
    if response.get("status") != "succeeded" or response.get("error") is not None or response.get("action") != row["action"] or response.get("request_id") != row["request_id"]:
        raise SystemExit("Raw response does not match snapshot request identity")
    data = response.get("data")
    if not isinstance(data, dict):
        raise SystemExit("Missing raw detail data")
    if row["action"] == "instagram.v2.fetch_post_info":
        candidates = [data.get("data")]
    elif row["action"] == "instagram.v3.get_post_info":
        candidates = data.get("items")
    else:
        raise SystemExit("Unsupported detail action")
    if not isinstance(candidates, list):
        raise SystemExit("Missing raw post list")
    matches = [p for p in candidates if isinstance(p, dict) and p.get("code") == row["code"]]
    if len(matches) != 1:
        raise SystemExit("Raw response must contain exactly one matching shortcode")
    post = matches[0]
    raw_id = post.get("id")
    if raw_id is not None and not ((isinstance(raw_id, str) and raw_id.strip()) or (type(raw_id) is int and 0 <= raw_id <= 9007199254740991)):
        raise SystemExit("Unsafe or malformed raw post ID")
    identity = "" if raw_id is None else str(raw_id)
    if identity.lstrip().startswith(("=", "+", "-", "@")):
        identity = "'" + identity
    if identity != row["id"]:
        raise SystemExit("CSV post identity differs from raw response")
    metrics = post.get("metrics") if row["action"] == "instagram.v2.fetch_post_info" else post
    if not isinstance(metrics, dict):
        raise SystemExit("Missing raw metric object")
    for field, key in (("likes", "like_count"), ("comments", "comment_count"), ("plays", "play_count")):
        value = metrics.get(key)
        if value is None:
            expected = ""
        else:
            if type(value) is int and 0 <= value <= 9007199254740991:
                expected = str(value)
            elif isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
                expected = str(int(value))
            else:
                raise SystemExit("Raw metric is not a safe integer or original ASCII digit string")
        if row[field] != expected:
            raise SystemExit("CSV metric differs from raw response; re-export instead of editing")
    return digest
before, after = load(before_file), load(after_file)
source_hashes = [verify_source(before), verify_source(after)]
allowed = {"instagram.v2.fetch_post_info", "instagram.v3.get_post_info"}
if before.get("action") not in allowed or after.get("action") not in allowed:
    raise SystemExit("Unsupported detail action")
if Path(before_file).resolve() == Path(after_file).resolve():
    raise SystemExit("Use two independently saved snapshot files")
for row in (before, after):
    if not row.get("request_id") or not row.get("source_file"):
        raise SystemExit("Each snapshot needs its request ID and raw-response source")
if before["request_id"] == after["request_id"] or before["source_file"] == after["source_file"]:
    raise SystemExit("The snapshots must represent distinct saved queries")
if before["code"] != after["code"]:
    raise SystemExit("Cannot compare different posts")
if before.get("id") and after.get("id") and before["id"] != after["id"]:
    raise SystemExit("Conflicting post identity")
if not before.get("action") or before["action"] != after.get("action"):
    raise SystemExit("Use the same detail action for both observations")
elapsed = (stamp(after_time) - stamp(before_time)).total_seconds()
if elapsed <= 0:
    raise SystemExit("Follow-up must be later than baseline")
result = {"code": before["code"], "action": before["action"], "before_file": before_file,
          "after_file": after_file, "before_collected_at": before_time, "after_collected_at": after_time,
          "before_request_id": before.get("request_id"), "after_request_id": after.get("request_id"),
          "elapsed_seconds": elapsed, "source_sha256": source_hashes,
          "raw_identity_and_metrics_verified": True, "query_times": "caller_recorded_not_server_attested", "metrics": {}}
for field in ("likes", "comments", "plays"):
    values = []
    for row in (before, after):
        value = row.get(field, "")
        if value == "":
            values.append(None)
            continue
        try:
            number = Decimal(value)
            if not number.is_finite() or number < 0 or number != number.to_integral_value():
                raise InvalidOperation
        except InvalidOperation:
            raise SystemExit(f"Invalid {field} counter")
        values.append(int(number))
    a, b = values
    result["metrics"][field] = {"before": a, "after": b, "net_change": b - a if a is not None and b is not None else None}
result["scope"] = "two public observations; not reach, attribution or follower growth"
with Path(output).open("x", encoding="utf-8") as handle:
    json.dump(result, handle, ensure_ascii=False, indent=2)
```

## Evidence check before sending the change report

`instagram_snapshot.py` records the raw response's absolute path and SHA-256 in the CSV. `compare_instagram.py` re-reads both raw files and verifies the status, action, request ID, shortcode, generic post ID and all three counters. An edited CSV count, a substituted response or changed source bytes stop the report. A CSV exported without the hash must be re-exported from its saved JSON; re-exporting makes no new API call. Keep the raw files at the recorded paths, or re-export after moving the raw files.

The hash detects changes relative to the saved CSV; the hash is not a server signature and cannot prove that a CSV and JSON edited together are authentic. The query times are recorded by the caller. `caption` and `username` are context; `compare_instagram.py` does not verify them. The generic `id` column is not the numeric `media_id` that comment requests need; for comments, use the [detail-to-comments handoff](/faq/instagram-url-and-id).

For a client report, attach both source JSON files, the two CSVs and `instagram-change.json`. Write: “Over this recorded observation interval, this post's reported likes changed from A to B, a net change of B−A.” Keep a missing metric as unavailable, explain negative revisions, and do not label the difference as reach, conversions or paid-campaign lift. Neither local script sends a request.

Put the follow-up request in a different directory such as `instagram-query-2`; the `mkdir ... && curl ...` command stops when the directory already exists instead of overwriting earlier evidence. Record each query's actual timezone-aware time when you collect the response, not the later CSV export time. A failed curl can leave error headers and an error body for diagnosis; those files are not a successful snapshot.

## Why does an apparently numeric value stop the report?

Each count must be a nonnegative JSON integer within the exact safe-integer range, or an original ASCII digit string. `0` stays zero, and a missing counter stays unavailable. Decimal or exponent strings, floats, booleans, rounded display labels and integers outside the safe range stop both the export and the comparison; never convert such values to zero or strip punctuation from them. An original digit string above the safe-integer limit stays exact in Python. A generic post ID must not be rebuilt from a rounded number either.

If a file fails the count check, keep the file and record “not comparable: invalid or precision-unsafe source value”. Do not edit the raw JSON and its hash to force a client result, and do not spend on another call automatically. To compare against an older snapshot, re-export the older snapshot from its saved raw response first. A response with a successful outer status and a non-null `error` is rejected by both scripts.