Tutorial · Instagram · Python

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 requests package (pip install requests). csv, os and 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.

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()
Tested 2026-12-02 against the documented API responses on Python 3.9.6. Run: python instagram_profiles.py usernames.txt

Run it

  1. 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.
  2. Set HANDLEHAUL_API_KEY. Export the key as the environment variable HANDLEHAUL_API_KEY so it never sits in the code.
  3. Install requests. Run pip install requests. Python 3.9 or newer is required; everything else is in the standard library.
  4. Save the script as instagram_profiles.py. Copy the script above into instagram_profiles.py, and put your input in usernames.txt, one item per line.
  5. 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:

usernames.txt
natgeo
@NatGeo
# lines starting with # are skipped
nosuchaccount_0000
Terminal
export HANDLEHAUL_API_KEY=kd_live_...   # your key from the dashboard
pip install requests
python instagram_profiles.py usernames.txt
On Windows PowerShell, set the key with $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.

Calls and cost for bulk instagram profiles to csv
JobCallsCost
100 profiles100$0.14 to $0.080
1,000 profiles1,000$1.40 to $0.80
10,000 profiles10,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.

Terminal
natgeo: 280000000 followers
nosuchaccount_0000: user_not_found
Saved 1 of 2 profiles to profiles.csv (1 credits)
profiles.csv
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.

Errors this script can meet and what it does
Status and codeWhenWhat the script does
404 user_not_foundNo account with that usernameThe script writes a row with the error code and goes on (failed calls are free).
403 private_accountReturned instead of a profile in rare casesThe script writes a row with the error code and goes on (failed calls are free).
401 invalid_api_keyThe key is missing, wrong or revokedStops with the message. Check the variable with echo $HANDLEHAUL_API_KEY.
402 insufficient_creditsThe account is out of creditsStops. Rows already fetched stay in the file.
429 rate_limitedToo many requests per secondWaits for Retry-After and retries, up to 5 times. Not charged.
502 / 503 / 504Data temporarily unavailable or slowRetries 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.

Python SDK
# 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"])
Source and reference: handlehaul-python on GitHub.

Next steps

Bulk Instagram profiles to CSV with Python: questions

Is there an official Instagram API for Python?
Meta’s Instagram API only serves professional accounts that log in to your app, and gives other accounts’ counts only through Business Discovery. For public profiles of any account, a public-data API like this one works with a plain API key. See Instagram Graph API alternative.
Can I look up profiles by user id instead of username?
Yes. Call /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?
A private account still returns its public profile fields (name, bio, counts) with is_private set to True. Its follower list and posts are not available through the API.
Can I make it faster with threads?
Yes, with 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.