# Detect new followers and follows with an API

> To detect new Instagram followers or new follows, read the first page of a newest-first list and keep the rows above the first account you saw last time. One page per check instead of the whole list. Python and Node.js code.

**Short answer:** to detect new followers or new follows, call `GET /v1/users/{user}/followers` (or `/following`), and keep the rows that sit **above the first account you already saw** last time. The Klupt API returns both lists newest first, so new accounts are always at the top: one page per check is enough, however big the account is.

> **Definition:** *newest-first diffing* compares only the top of a list sorted by follow time (newest first) with the last snapshot. *Full-list diffing* downloads the entire list in an unspecified order and compares it with the previous full copy. Both find new rows; only the first costs the same for a small and a huge account.

## Diff the full list or read the top?

Most Instagram scraping APIs return follower lists in an unspecified order, so the only way to find new followers is to download everything and compare sets. With newest-first lists you read the top page and stop:

| Account size | Diff the full list | Newest first: read the top |
|---|---|---|
| 1,000 followers | 40 pages, 40 credits ($0.08) | 1 page, 1 credit ($0.00) |
| 100,000 followers | 4,000 pages, 4,000 credits ($8.00) | 1 page, 1 credit ($0.00) |
| 1,000,000 followers | 40,000 pages, 40,000 credits ($80.00) | 1 page, 1 credit ($0.00) |

Cost at the base price of $2.00 per 1,000 credits, 25 followers per page. Following pages hold about 200 accounts for 2 credits, so the gap is the same there.

## The algorithm

1. Read page one of the list.
2. Walk down from `position: 1`. Every account that is **not** in your last snapshot is new. Stop at the first account that **is** in it.
3. If you reach the end of the page without meeting a known account, more new accounts arrived than fit on one page: read the next page (`?cursor=` with `pagination.next_cursor`) and keep walking. Cap it, for example at 5 pages.
4. Save the ids from this page as the new snapshot.

Compare by `id`, not `username`: usernames can change, ids never do. Keep the whole last page as the snapshot rather than one "last seen" account, so that one account leaving does not break the comparison.

```bash
curl "https://api.klupt.io/v1/users/natgeo/followers" \
  -H "X-Api-Key: $KLUPT_API_KEY"
```

```python
import json, os, pathlib, requests

API = "https://api.klupt.io/v1"
H = {"X-Api-Key": os.environ["KLUPT_API_KEY"]}

def new_rows(user, kind="followers", max_pages=5):
    snap = pathlib.Path(f"{user}-{kind}.json")
    known = set(json.loads(snap.read_text())) if snap.exists() else None
    new, cursor, first_page = [], None, None
    for _ in range(max_pages):
        params = {"cursor": cursor} if cursor else {}
        r = requests.get(f"{API}/users/{user}/{kind}", headers=H, params=params, timeout=30)
        r.raise_for_status()
        body = r.json()
        if first_page is None:
            first_page = body["data"]
        if known is None:
            break  # first run: just take a snapshot
        hit = next((i for i, row in enumerate(body["data"]) if row["id"] in known), None)
        new += body["data"] if hit is None else body["data"][:hit]
        cursor = body["pagination"]["next_cursor"]
        if hit is not None or not cursor:
            break
    snap.write_text(json.dumps([row["id"] for row in first_page]))
    return new

print([r["username"] for r in new_rows("natgeo")])
```

```javascript
import { readFile, writeFile } from "node:fs/promises";

const API = "https://api.klupt.io/v1";
const headers = { "X-Api-Key": process.env.KLUPT_API_KEY };

async function newRows(user, kind = "followers", maxPages = 5) {
  const file = `${user}-${kind}.json`;
  const known = await readFile(file, "utf8").then((t) => new Set(JSON.parse(t))).catch(() => null);
  const fresh = [];
  let cursor = null;
  let firstPage = null;
  for (let page = 0; page < maxPages; page++) {
    const qs = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
    const res = await fetch(`${API}/users/${user}/${kind}${qs}`, { headers });
    const body = await res.json();
    if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
    firstPage ??= body.data;
    if (!known) break; // first run: just take a snapshot
    const stop = body.data.findIndex((r) => known.has(r.id));
    fresh.push(...(stop === -1 ? body.data : body.data.slice(0, stop)));
    cursor = body.pagination.next_cursor;
    if (stop !== -1 || !cursor) break;
  }
  await writeFile(file, JSON.stringify(firstPage.map((r) => r.id)));
  return fresh;
}

console.log((await newRows("natgeo")).map((r) => r.username));
```

```php
$ch = curl_init("https://api.klupt.io/v1/users/natgeo/followers");
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => ["X-Api-Key: " . getenv("KLUPT_API_KEY")],
    CURLOPT_RETURNTRANSFER => true,
]);
$body = json_decode(curl_exec($ch), true);
print_r($body["data"]);
```

```go
req, _ := http.NewRequest("GET", "https://api.klupt.io/v1/users/natgeo/followers", nil)
req.Header.Set("X-Api-Key", os.Getenv("KLUPT_API_KEY"))
res, err := http.DefaultClient.Do(req)
if err != nil {
    log.Fatal(err)
}
defer res.Body.Close()
var body map[string]any
json.NewDecoder(res.Body).Decode(&body)
fmt.Println(body["data"])
```

The same function works for new follows: pass `"following"` instead of `"followers"`.

## Dating new rows

Instagram does not publish when a follow happened, so no API can give a follow date. What you can record is *when you first saw* an account at the top: check on a schedule and store that time with each new row. Checked hourly, that is accurate to the hour.

## Unfollows are a different problem

An account that leaves can sit anywhere in the list, so the top of the list does not show it. Spotting one needs the whole list, and a page can now and then come back one row short. Never report an unfollow from a single missing row: confirm it over several checks ([Newest-first order](/docs/newest-first-order)).

## FAQ

### How do I get notified when an Instagram account gets a new follower?
Check GET /v1/users/{user}/followers on a schedule (for example hourly) and compare the top rows with your last snapshot. The list is newest first, so every account above the first one you already knew is a new follower.

### Do I have to download the whole follower list to find new followers?
No. With a newest-first list the new followers are always on page one. You read more pages only when more new followers arrived since the last check than fit on one page (25 per page).

### How do I detect new accounts someone follows?
Use the same comparison on GET /v1/users/{user}/following, which returns about 200 accounts a page, newest first, for 2 credits. See [Who someone recently followed](/docs/who-someone-recently-followed-api).

### Can the API tell me exactly when a follow happened?
No. Instagram does not share follow dates. Record the time your check first saw the account at the top of the list instead.

### Should I compare usernames or ids?
Ids. A username can change; the numeric id never does. Every row in the list carries both.
