Instagram API in Python: bulk profiles to CSV
To pull Instagram profiles in Python, send each username to /v1/instagram/users/by-username/{username} with requests and write the counts, bio and category to a CSV. The script below reads a list of usernames, skips duplicates, notes accounts that do not exist and stops cleanly on anything else.
Short answer. Put one username per line in usernames.txt, set HANDLEHAUL_API_KEY and run python instagram_profiles.py usernames.txt. You get profiles.csv with followers, following, posts, verified, business category, bio and the numeric id. 1,000 profiles cost $1.40 to $0.80; usernames with no account are free.
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/by-username/{username} (see the Instagram profile API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as instagram_profiles.py.
# Fetch public Instagram profiles for a list of usernames and save them to CSV.
# Usage: python instagram_profiles.py usernames.txt (one username per line)
# 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 = ["input", "id", "username", "full_name", "followers", "following", "posts", "is_private",
"is_verified", "is_business", "category", "external_url", "biography", "error"]
SKIP = {"user_not_found", "private_account"} # note these and go on (failed calls are free)
def main():
if len(sys.argv) < 2:
sys.exit("Usage: python instagram_profiles.py usernames.txt")
with open(sys.argv[1], encoding="utf-8") as f:
names = [line.strip().lstrip("@") for line in f if line.strip() and not line.startswith("#")]
names = list(dict.fromkeys(n.lower() for n in names)) # drop duplicates: each call costs a credit
out = "profiles.csv"
done, credits, error = 0, 0, None
with open(out, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS)
writer.writeheader()
for name in names:
try:
body = get(f"/v1/instagram/users/by-username/{quote(name, safe='')}")
except ApiError as e:
if e.code not in SKIP:
error = e
break
writer.writerow({"input": name, "error": e.code})
print(f"{name}: {e.code}")
continue
except requests.RequestException as e:
error = e
break
p, counts = body["data"], body["data"]["counts"]
credits += body["meta"].get("credits_charged", 0)
writer.writerow({
"input": name, "id": p["id"], "username": p["username"], "full_name": p["full_name"],
"followers": counts["followers"], "following": counts["following"], "posts": counts["posts"],
"is_private": p["is_private"], "is_verified": p["is_verified"], "is_business": p["is_business"],
"category": p["category"], "external_url": p["external_url"], "biography": p["biography"],
"error": "",
})
done += 1
print(f"{name}: {counts['followers']} followers")
if error:
sys.exit(f"Stopped: {error}\n{done} profiles saved in {out}")
print(f"Saved {done} of {len(names)} profiles to {out} ({credits:g} credits)")
if __name__ == "__main__":
main()
python instagram_profiles.py usernames.txtRun 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_profiles.py. Copy the script above into
instagram_profiles.py, and put your input inusernames.txt, one item per line. - Run it. Run
python instagram_profiles.py usernames.txt. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.
Example usernames.txt:
natgeo
@NatGeo
# lines starting with # are skipped
nosuchaccount_0000
export HANDLEHAUL_API_KEY=kd_live_... # your key from the dashboard
pip install requests
python instagram_profiles.py usernames.txt
$env:HANDLEHAUL_API_KEY="kd_live_...".How it works
One call per username. The script calls /v1/instagram/users/by-username/{username} for each line. This route always reads its input as a username, so all-digit usernames work as they are.
Duplicates. Usernames are lower-cased and de-duplicated before any call, because each successful call is charged. A leading @ is dropped.
Missing and private accounts. A username with no account answers 404 user_not_found: the script writes the code in the error column and goes on, and the call is free. A private account still returns its public profile fields with is_private set to true; its follower list and posts are not available.
Keep the id. Every row carries the numeric id. Ids survive username changes: store them and use /v1/instagram/users/by-id/{id} next time, or pass the id to the followers and posts endpoints to skip the lookup credit.
Freshness. Profiles are cached for 60 seconds and a cached answer is free; meta.cache_age_seconds says how old it is. Add fresh=true to force a live fetch.
What it costs
Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per profile that exists. Usernames with no account, and answers from the 60-second cache, are free.
| Job | Calls | Cost |
|---|---|---|
| 100 profiles | 100 | $0.14 to $0.080 |
| 1,000 profiles | 1,000 | $1.40 to $0.80 |
| 10,000 profiles | 10,000 | $14.00 to $8.00 |
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.
natgeo: 280000000 followers
nosuchaccount_0000: user_not_found
Saved 1 of 2 profiles to profiles.csv (1 credits)
input,id,username,full_name,followers,following,posts,is_private,is_verified,is_business,category,external_url,biography,error
natgeo,787132,natgeo,National Geographic,280000000,160,30500,False,True,True,Media/news company,https://www.nationalgeographic.com,Experience the world through the eyes of our photographers.,
nosuchaccount_0000,,,,,,,,,,,,,user_not_found
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 |
|---|---|---|
404 user_not_found | No account with that username | The script writes a row with the error code and goes on (failed calls are free). |
403 private_account | Returned instead of a profile in rare cases | The script writes a row with the error code and goes on (failed calls are free). |
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
p = hh.instagram.profile_by_username("natgeo").data
print(p["id"], p["counts"]["followers"], p["category"])
Next steps
- Bulk Instagram profiles to CSV with Node.js: the same script in Node.js.
- Instagram profile API: what the endpoint returns and how it compares.
- Instagram profile API docs: every parameter, field and error.
- All tutorials: other jobs on Instagram and TikTok, in Python and Node.js.
Bulk Instagram profiles to CSV with Python: questions
Is there an official Instagram API for Python?
Can I look up profiles by user id instead of username?
/v1/instagram/users/by-id/{id} with the numeric id. Ids do not change when someone renames the account, so store the id column and use it next time.What happens with private accounts?
is_private set to True. Its follower list and posts are not available through the API.Can I make it faster with threads?
concurrent.futures.ThreadPoolExecutor and a few workers, but stay under your account’s requests-per-second limit (see rate limits). The script’s retry on 429 covers short bursts.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.