Export Instagram followers to CSV with Python
To scrape an Instagram account’s followers with Python, call /v1/instagram/users/{user}/followers with requests, follow pagination.next_cursor 25 rows at a time and write each page to a CSV. The script below does exactly that, newest followers first, and stops after the number of pages you choose.
Short answer. Save the script, set HANDLEHAUL_API_KEY, run python instagram_followers.py natgeo 4 and you get natgeo_followers.csv with the 100 most recent followers. Each page of 25 is one call: 1,000 followers take 40 calls, $0.056 to $0.032. Public accounts only.
Facts checked 2 December 2026. Prices change: follow the links before you decide.
What you need
- An API key. Sign up and create one in the dashboard. A sandbox key (
kd_test_) returns sample data for free, so you can run the script before you spend anything. - Python 3.9 or newer and the
requestspackage (pip install requests).csv,osand the rest come with Python. - The key in
HANDLEHAUL_API_KEY. The script reads it from the environment, so the key never sits in your code or your repository. - Public Instagram accounts. The API returns public data only: no logins, no private accounts, no DMs.
The script
It calls GET /v1/instagram/users/{user}/followers (see the Instagram followers API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as instagram_followers.py.
# Export the followers of a public Instagram account to CSV, newest first.
# Usage: python instagram_followers.py <username or numeric id> [max_pages]
# Needs Python 3.9+, the requests package and HANDLEHAUL_API_KEY in the environment.
import csv
import os
import sys
import time
from urllib.parse import quote
import requests
API = "https://api.handlehaul.com"
KEY = os.environ.get("HANDLEHAUL_API_KEY")
if not KEY:
sys.exit("Set HANDLEHAUL_API_KEY first, e.g. export HANDLEHAUL_API_KEY=kd_live_...")
session = requests.Session()
session.headers["X-Api-Key"] = KEY
class ApiError(Exception):
def __init__(self, status, code, message):
super().__init__(f"HTTP {status} {code}: {message}")
self.status = status
self.code = code
def get(path, params=None):
# One API call. Waits and retries on 429 (honouring Retry-After) and on 502/503/504,
# raises ApiError for any other error. Failed calls and 429 answers are not charged.
for attempt in range(6):
r = session.get(API + path, params=params, timeout=60)
if r.status_code in (429, 502, 503, 504) and attempt < 5:
try:
wait = float(r.headers.get("Retry-After", ""))
except ValueError:
wait = 2 ** attempt
print(f" HTTP {r.status_code}, retrying in {wait:g}s", file=sys.stderr)
time.sleep(wait)
continue
try:
body = r.json()
except ValueError:
body = {}
if r.ok:
return body
err = body.get("error") or {}
raise ApiError(r.status_code, err.get("code", "unknown"), err.get("message", r.text[:200]))
FIELDS = ["position", "id", "username", "full_name", "is_private", "is_verified", "profile_pic_url"]
def main():
if len(sys.argv) < 2:
sys.exit("Usage: python instagram_followers.py <username or numeric id> [max_pages]")
user = sys.argv[1] # all digits = numeric id; write @12345 for an all-digit username
max_pages = int(sys.argv[2]) if len(sys.argv) > 2 else 4 # 25 followers a page
out = f"{user.lstrip('@')}_followers.csv"
path = f"/v1/instagram/users/{quote(user, safe='')}/followers"
params, pages, rows, credits, error = {}, 0, 0, 0, None
with open(out, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore")
writer.writeheader()
try:
while pages < max_pages:
body = get(path, params)
pages += 1
meta = body["meta"]
credits += meta.get("credits_charged", 0)
if meta.get("list_hidden"):
print("This account hides its followers from everyone.")
break
if meta.get("order") == "unspecified":
print(f" page {pages} is not in newest-first order", file=sys.stderr)
writer.writerows(body["data"])
rows += len(body["data"])
print(f"page {pages}: {rows} followers")
if not body["pagination"]["has_more"]:
break
params = {"cursor": body["pagination"]["next_cursor"]}
except (ApiError, requests.RequestException) as e:
error = e
if error:
sys.exit(f"Stopped: {error}\n{rows} followers saved in {out}")
print(f"Saved {rows} followers to {out} ({pages} pages, {credits:g} credits)")
if __name__ == "__main__":
main()
python instagram_followers.py natgeo 4Run it
- Get an API key. Sign up at api.handlehaul.com/signup and create a key. A sandbox key (
kd_test_) returns sample data for free while you test. - Set HANDLEHAUL_API_KEY. Export the key as the environment variable
HANDLEHAUL_API_KEYso it never sits in the code. - Install requests. Run
pip install requests. Python 3.9 or newer is required; everything else is in the standard library. - Save the script as instagram_followers.py. Copy the script above into
instagram_followers.py. - Run it. Run
python instagram_followers.py natgeo 4. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.
export HANDLEHAUL_API_KEY=kd_live_... # your key from the dashboard
pip install requests
python instagram_followers.py natgeo 4
$env:HANDLEHAUL_API_KEY="kd_live_...".How it works
Paging. Each call to /v1/instagram/users/{user}/followers returns up to 25 followers and a pagination object. The script sends pagination.next_cursor back as ?cursor= until has_more is false or it has read max_pages pages. Cursors are opaque and signed: pass them back unchanged.
Order. position: 1 is the account’s most recent follower, so page one holds the newest rows. meta.order says newest_first; on the rare call where it says unspecified, the script prints a warning. Instagram shares no follow dates with anyone, so there is no “followed at” column.
Hidden lists. When meta.list_hidden is true, the account hides its followers from everyone: the page is empty and the script stops.
One row short. Now and then a page misses one account while the rest stay in order. Never treat an account missing from one run as an unfollow; confirm it over several runs.
Usernames and ids. Naming an account by a handle we have not looked up in the last 7 days adds 1 lookup credit; send the numeric id from any result to skip it. The script takes either: natgeo or 787132. Get the id once from a profile call (or the profiles tutorial) and reuse it.
What it costs
Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per page of 25. Add 1 lookup credit when you name the account by a username we have not looked up in the last 7 days. Pages served from cache are free.
| Job | Calls | Cost |
|---|---|---|
| Newest 100 followers | 4 | $0.0056 to $0.0032 |
| 1,000 followers | 40 | $0.056 to $0.032 |
| 10,000 followers | 400 | $0.56 to $0.32 |
The script makes one call at a time, well under the account limit of 10 to 30 requests per second. Each response says what it cost in meta.credits_charged, and the script adds those up in its last line.
Sample output
An example run with example values, not a real export. Field names and shapes are the ones in the API docs.
page 1: 25 followers
page 2: 50 followers
page 3: 75 followers
page 4: 100 followers
Saved 100 followers to natgeo_followers.csv (4 pages, 4 credits)
position,id,username,full_name,is_private,is_verified,profile_pic_url
1,6860189,new_follower,New Follower,False,False,https://scontent.cdninstagram.com/…
2,3141592,coffee.place,Coffee Place,False,False,https://scontent.cdninstagram.com/…
Common errors
Errors come back as { "error": { "code", "message", "request_id" } } with an HTTP status. Failed calls are never charged. Full list: error codes.
| Status and code | When | What the script does |
|---|---|---|
403 private_account | The account is private | Stops. Private lists are not available. Free. |
404 user_not_found | No account with that username or id | Stops. Free. Check the spelling, or write @12345 for an all-digit username. |
400 invalid_cursor | A cursor from another account or endpoint | Stops. Start again without a cursor. |
401 invalid_api_key | The key is missing, wrong or revoked | Stops with the message. Check the variable with echo $HANDLEHAUL_API_KEY. |
402 insufficient_credits | The account is out of credits | Stops. Rows already fetched stay in the file. |
429 rate_limited | Too many requests per second | Waits for Retry-After and retries, up to 5 times. Not charged. |
502 / 503 / 504 | Data temporarily unavailable or slow | Retries with a growing wait (1, 2, 4, 8, 16 s). Failed calls are free. |
The same job with the SDK
If you would rather not maintain the HTTP code, the official Python SDK (pip install handlehaul) does the paging, retries 429 for you and raises typed errors. The script above is the same job with every request visible.
# pip install handlehaul
from handlehaul import HandleHaul
hh = HandleHaul() # reads HANDLEHAUL_API_KEY
for user in hh.instagram.followers.iterate("natgeo", max_pages=4):
print(user["position"], user["username"])
Next steps
- Export Instagram followers to CSV with Node.js: the same script in Node.js.
- Instagram followers API: what the endpoint returns and how it compares.
- Instagram followers API docs: every parameter, field and error.
- All tutorials: other jobs on Instagram and TikTok, in Python and Node.js.
Export Instagram followers to CSV with Python: questions
Can I scrape Instagram followers with Python without logging in?
How do I get every follower, not just the newest?
python instagram_followers.py natgeo 400 for up to 10,000 followers. The script stops by itself when has_more is false. Each page is one call, so check the cost table first: 10,000 followers is 400 calls.Why use requests and not instaloader or instagrapi?
How do I load the CSV into pandas?
pd.read_csv("natgeo_followers.csv") reads it as is: pandas drops the UTF-8 byte order mark the script writes for Excel. position 1 is the newest follower.Related
Instagram followers API
Follower lists newest first, 25 a page, for audience research.
Read more →The same in Node.js
Export Instagram followers to CSV with Node.js: same output, built-in fetch, no packages.
Read more →Instagram profile API
Counts, bio and the numeric id of any public account.
Read more →Run it on your own list
One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls are free.
Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.