Instagram and TikTok API in Python
Two ways to call HandleHaul from Python: a 60-line client on requests that you own, or the official handlehaul package (sync and async). Both page with the cursor and retry 429 answers.
Short answer. pip install handlehaul, set HANDLEHAUL_API_KEY, then HandleHaul().instagram.followers("natgeo") returns one page as page.data. Prefer no dependency beyond requests? Copy the client below. Python 3.9 or newer for both.
Facts checked 2 December 2026. Prices change: follow the links before you decide.
Set up
- Create a key in the dashboard and export it, so it never sits in your code or repository:
export HANDLEHAUL_API_KEY=kd_live_...(PowerShell:$env:HANDLEHAUL_API_KEY="kd_live_..."). Akd_test_key returns sample data in the live shape for free. - Install one of:
pip install requestsfor the hand-written client, orpip install handlehaulfor the SDK (it bringshttpx).
A client on requests
Client.get()makes one call, reuses the connection throughrequests.Session, waits out429usingRetry-Afterand retries502,503and504with a growing wait. Those answers are never charged, so retrying costs nothing.Client.paginate()is a generator: it fetches the next page only when you ask for more rows, so breaking out of the loop stops the spending. Each page is one call.- Errors raise
HandleHaulErrorwithstatus,codeandrequest_id. Do not retry400,401,402,403or404: the answer will not change.
handlehaul_client.pyInstall: pip install requestsRun: python handlehaul_client.py
"""A small HandleHaul API client with requests: retries, cursor paging and clear errors.
pip install requests
export HANDLEHAUL_API_KEY=kd_live_... # or a free kd_test_ key for sample data
python handlehaul_client.py
"""
import os
import random
import time
import requests
API = "https://api.handlehaul.com/v1"
RETRY = {429, 502, 503, 504} # never charged; everything else 4xx will not change on a retry
class HandleHaulError(Exception):
def __init__(self, status, code, message, request_id=None):
super().__init__(f"{status} {code}: {message}")
self.status, self.code, self.request_id = status, code, request_id
class Client:
def __init__(self, api_key=None, max_tries=5):
self.session = requests.Session() # reuses the connection between calls
self.session.headers["X-Api-Key"] = api_key or os.environ["HANDLEHAUL_API_KEY"]
self.max_tries = max_tries
self.credits = 0 # what this client spent, from meta.credits_charged
def get(self, path, **params):
"""One call. Retries 429 (after Retry-After) and 502/503/504 (growing wait)."""
for attempt in range(self.max_tries):
r = self.session.get(API + path, params=params, timeout=60)
if r.status_code in RETRY and attempt < self.max_tries - 1:
wait = r.headers.get("Retry-After")
time.sleep(float(wait) if wait else 2 ** attempt + random.random())
continue
body = r.json()
if not r.ok:
err = body.get("error", {})
raise HandleHaulError(r.status_code, err.get("code"), err.get("message"), err.get("request_id"))
self.credits += body["meta"].get("credits_charged", 0)
return body
raise HandleHaulError(429, "rate_limited", "still limited after retries")
def paginate(self, path, max_pages=10, **params):
"""Yield every row of a list endpoint, one page (one call) at a time. Stop early to stop paying."""
for _ in range(max_pages):
body = self.get(path, **params)
yield from body["data"]
if not body["pagination"]["has_more"]:
return
params["cursor"] = body["pagination"]["next_cursor"]
if __name__ == "__main__":
hh = Client()
profile = hh.get("/instagram/users/natgeo")["data"]
print(profile["username"], profile["counts"]["followers"], "followers")
for row in hh.paginate(f"/instagram/users/{profile['id']}/followers", max_pages=2):
print(row["position"], row["username"])
try:
hh.get("/instagram/users/private_demo/followers")
except HandleHaulError as e:
print("expected error:", e.code)
print("credits used:", hh.credits)
The official SDK
from handlehaul import HandleHaul. Methods follow the routes:hh.instagram.followers(),hh.instagram.post_comments(),hh.tiktok.transcript(),hh.tiktok.search(). List methods return one page;.iterate()yields rows across pages and.pages()yields pages, both withlimitandmax_pages.- It retries
429,5xx, timeouts and network errors twice by default (max_retries), waiting forRetry-Afterup to 30 seconds (max_retry_after). Errors are typed:RateLimitError,PrivateAccountError,NotFoundError,InsufficientCreditsError, all subclasses ofHandleHaulError. AsyncHandleHaulhas the same methods withawait. Below: several profiles at once, with a semaphore so you stay under your plan's speed limit.
handlehaul_async.pyInstall: pip install handlehaulRun: python handlehaul_async.py
"""Many profiles at once with the official SDK's async client (pip install handlehaul).
export HANDLEHAUL_API_KEY=kd_live_...
python handlehaul_async.py
"""
import asyncio
from handlehaul import AsyncHandleHaul, HandleHaulError
HANDLES = ["natgeo", "nasa", "private_demo", "bbcnews"]
LIMIT = asyncio.Semaphore(5) # stay well under your plan's requests per second
async def profile(hh, handle):
async with LIMIT:
try:
res = await hh.instagram.profile(handle)
return handle, res.data["counts"]["followers"], res.meta["credits_charged"]
except HandleHaulError as e: # 429s were already retried by the client
return handle, e.code, 0
async def main():
async with AsyncHandleHaul() as hh: # reads HANDLEHAUL_API_KEY
rows = await asyncio.gather(*(profile(hh, h) for h in HANDLES))
for handle, followers, credits in rows:
print(handle, followers)
print("credits used:", sum(r[2] for r in rows))
asyncio.run(main())
Every endpoint in Python
Each page below has a complete Python program for one route, plus the SDK version, the parameters, a sample response and what it costs. The link opens the Python tab.
| Tutorial | Route |
|---|---|
| Profile | GET /v1/instagram/users/{user} |
| Account details | GET /v1/instagram/users/{user}/account-details |
| Similar accounts | GET /v1/instagram/users/{user}/related |
| Followers | GET /v1/instagram/users/{user}/followers |
| Following | GET /v1/instagram/users/{user}/following |
| Posts | GET /v1/instagram/users/{user}/posts |
| Reels | GET /v1/instagram/users/{user}/reels |
| Tagged posts | GET /v1/instagram/users/{user}/tagged |
| Reposts | GET /v1/instagram/users/{user}/reposts |
| Post or reel | GET /v1/instagram/posts/{post} |
| Post stats (batch) | GET /v1/instagram/posts/stats |
| Comments | GET /v1/instagram/posts/{post}/comments |
| Comment replies | GET /v1/instagram/comments/{comment}/replies |
| Post likers | GET /v1/instagram/posts/{post}/likers |
| Comment likers | GET /v1/instagram/comments/{comment}/likers |
| Stories | GET /v1/instagram/users/{user}/stories |
| Story by id | GET /v1/instagram/stories/{story} |
| Highlights | GET /v1/instagram/users/{user}/highlights |
| Highlight stories | GET /v1/instagram/highlights/{highlight} |
| Search hashtags | GET /v1/instagram/search/hashtags |
| Hashtag | GET /v1/instagram/hashtags/{tag} |
| Hashtag posts | GET /v1/instagram/hashtags/{tag}/posts |
| Search places | GET /v1/instagram/search/places |
| Place | GET /v1/instagram/places/{place} |
| Place posts | GET /v1/instagram/places/{place}/posts |
| Search audio | GET /v1/instagram/search/audio |
| Trending audio | GET /v1/instagram/audio/trending |
| Audio | GET /v1/instagram/audio/{audio} |
| Reels using audio | GET /v1/instagram/audio/{audio}/reels |
| Search accounts | GET /v1/instagram/search/users |
| URL resolver | GET /v1/instagram/resolve |
TikTok
| Tutorial | Route |
|---|---|
| Profile | GET /v1/tiktok/users/{user} |
| Suggested accounts | GET /v1/tiktok/users/{user}/suggested |
| Followers | GET /v1/tiktok/users/{user}/followers |
| Following | GET /v1/tiktok/users/{user}/following |
| Posts | GET /v1/tiktok/users/{user}/posts |
| Reposts | GET /v1/tiktok/users/{user}/reposts |
| Liked videos | GET /v1/tiktok/users/{user}/liked |
| Playlists | GET /v1/tiktok/users/{user}/playlists |
| Stories | GET /v1/tiktok/users/{user}/stories |
| Video or photo post | GET /v1/tiktok/posts/{post} |
| Comments | GET /v1/tiktok/posts/{post}/comments |
| Comment replies | GET /v1/tiktok/comments/{comment}/replies |
| Transcript | GET /v1/tiktok/posts/{post}/transcript |
| Sound | GET /v1/tiktok/music/{music} |
| Posts using a sound | GET /v1/tiktok/music/{music}/posts |
| Hashtag | GET /v1/tiktok/hashtags/{tag} |
| Hashtag posts | GET /v1/tiktok/hashtags/{tag}/posts |
| Search | GET /v1/tiktok/search |
Python: questions
Is there a Python library for the HandleHaul API?
pip install handlehaul (source on GitHub as handlehaul-python). It has a sync client and an async one, typed responses, cursor helpers and retries. Plain requests works too: the API is JSON over HTTPS with one header.Can I scrape Instagram with Python without logging in?
How do I avoid 429 errors in Python?
Retry-After when a 429 arrives. The SDK does the waiting for you. Your account's speed limit is shared by all its keys, so extra keys do not add speed.Related
Instagram and TikTok API in Node.js
Call HandleHaul from Node.js 18 or newer with the built-in fetch, or install the typed handlehaul package from npm, which also ships a CLI.
Read more →Instagram and TikTok API in PHP
One class, PHP 8 and the curl extension: no Composer package needed.
Read more →Instagram and TikTok API in Go
A standard-library Go client with generic Page[T] and One[T] types: decode the fields you need into structs, page with a callback, and get a typed APIError for anything else.
Read more →Build it in Python
One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls and cache hits are free.
Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.