Tutorial · Python

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_..."). A kd_test_ key returns sample data in the live shape for free.
  • Install one of: pip install requests for the hand-written client, or pip install handlehaul for the SDK (it brings httpx).

A client on requests

  • Client.get() makes one call, reuses the connection through requests.Session, waits out 429 using Retry-After and retries 502, 503 and 504 with 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 HandleHaulError with status, code and request_id. Do not retry 400, 401, 402, 403 or 404: 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)
Tested 2026-12-02 against a local mock serving the documented API responses (retry on 429, cursor paging, a private-account error).

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 with limit and max_pages.
  • It retries 429, 5xx, timeouts and network errors twice by default (max_retries), waiting for Retry-After up to 30 seconds (max_retry_after). Errors are typed: RateLimitError, PrivateAccountError, NotFoundError, InsufficientCreditsError, all subclasses of HandleHaulError.
  • AsyncHandleHaul has the same methods with await. 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())
Tested 2026-12-02 against a local mock serving the documented API responses (retry on 429, cursor paging, a private-account error).

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.

Instagram

Instagram endpoint tutorials
TutorialRoute
ProfileGET /v1/instagram/users/{user}
Account detailsGET /v1/instagram/users/{user}/account-details
Similar accountsGET /v1/instagram/users/{user}/related
FollowersGET /v1/instagram/users/{user}/followers
FollowingGET /v1/instagram/users/{user}/following
PostsGET /v1/instagram/users/{user}/posts
ReelsGET /v1/instagram/users/{user}/reels
Tagged postsGET /v1/instagram/users/{user}/tagged
RepostsGET /v1/instagram/users/{user}/reposts
Post or reelGET /v1/instagram/posts/{post}
Post stats (batch)GET /v1/instagram/posts/stats
CommentsGET /v1/instagram/posts/{post}/comments
Comment repliesGET /v1/instagram/comments/{comment}/replies
Post likersGET /v1/instagram/posts/{post}/likers
Comment likersGET /v1/instagram/comments/{comment}/likers
StoriesGET /v1/instagram/users/{user}/stories
Story by idGET /v1/instagram/stories/{story}
HighlightsGET /v1/instagram/users/{user}/highlights
Highlight storiesGET /v1/instagram/highlights/{highlight}
Search hashtagsGET /v1/instagram/search/hashtags
HashtagGET /v1/instagram/hashtags/{tag}
Hashtag postsGET /v1/instagram/hashtags/{tag}/posts
Search placesGET /v1/instagram/search/places
PlaceGET /v1/instagram/places/{place}
Place postsGET /v1/instagram/places/{place}/posts
Search audioGET /v1/instagram/search/audio
Trending audioGET /v1/instagram/audio/trending
AudioGET /v1/instagram/audio/{audio}
Reels using audioGET /v1/instagram/audio/{audio}/reels
Search accountsGET /v1/instagram/search/users
URL resolverGET /v1/instagram/resolve

TikTok

TikTok endpoint tutorials
TutorialRoute
ProfileGET /v1/tiktok/users/{user}
Suggested accountsGET /v1/tiktok/users/{user}/suggested
FollowersGET /v1/tiktok/users/{user}/followers
FollowingGET /v1/tiktok/users/{user}/following
PostsGET /v1/tiktok/users/{user}/posts
RepostsGET /v1/tiktok/users/{user}/reposts
Liked videosGET /v1/tiktok/users/{user}/liked
PlaylistsGET /v1/tiktok/users/{user}/playlists
StoriesGET /v1/tiktok/users/{user}/stories
Video or photo postGET /v1/tiktok/posts/{post}
CommentsGET /v1/tiktok/posts/{post}/comments
Comment repliesGET /v1/tiktok/comments/{comment}/replies
TranscriptGET /v1/tiktok/posts/{post}/transcript
SoundGET /v1/tiktok/music/{music}
Posts using a soundGET /v1/tiktok/music/{music}/posts
HashtagGET /v1/tiktok/hashtags/{tag}
Hashtag postsGET /v1/tiktok/hashtags/{tag}/posts
SearchGET /v1/tiktok/search

Python: questions

Is there a Python library for the HandleHaul API?
Yes: 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?
Yes. The API returns public data only and never logs in to Instagram or TikTok, so your code never handles an account, a session or a challenge. Private accounts answer 403 private_account, and that call is free.
How do I avoid 429 errors in Python?
Keep concurrency low (a semaphore of a few calls) and honour 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.

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.