Tutorial · PHP

Instagram and TikTok API in PHP

One class, PHP 8 and the curl extension: no Composer package needed. It retries 429 answers, pages with a generator and throws an exception with the API error code.

Short answer. Send GET https://api.handlehaul.com/v1/... with the header X-Api-Key, decode the JSON, and follow pagination.next_cursor. The class below does that with retries; copy it into your project or framework service container.

Facts checked 2 December 2026. Prices change: follow the links before you decide.

Set up

  • PHP 8.1 or newer with the curl extension (php -m | grep curl). Put the key in the environment (HANDLEHAUL_API_KEY), your framework's .env or a secrets store, never in the code.
  • Decode with JSON_BIGINT_AS_STRING: Instagram and TikTok ids can be larger than PHP's integer range on some systems, and the API sends them as strings anyway.

The client class

  • get() reads Retry-After from the response headers through CURLOPT_HEADERFUNCTION, sleeps that long on 429, and retries 502, 503 and 504 with a growing wait. Those answers are free.
  • paginate() returns a Generator: rows arrive page by page, and a break in your foreach stops the next call. Errors throw HandleHaulException with status and errorCode.
  • In Laravel or Symfony, register the class as a singleton and inject it; the client holds no state except the credit counter.

HandleHaul.phpRun: php HandleHaul.php

<?php
// A small HandleHaul API client for PHP 8 (curl extension): retries, cursor paging and clear errors.
//   export HANDLEHAUL_API_KEY=kd_live_...   (or a free kd_test_ key for sample data)
//   php HandleHaul.php

final class HandleHaulException extends RuntimeException
{
    public function __construct(public readonly int $status, public readonly ?string $errorCode, string $message)
    {
        parent::__construct("$status $errorCode: $message");
    }
}

final class HandleHaul
{
    private const API = "https://api.handlehaul.com/v1";
    private const RETRY = [429, 502, 503, 504]; // never charged; other 4xx answers will not change on a retry
    public int $credits = 0; // what this client spent, from meta.credits_charged

    public function __construct(private ?string $apiKey = null, private int $maxTries = 5)
    {
        $this->apiKey ??= getenv("HANDLEHAUL_API_KEY") ?: throw new RuntimeException("Set HANDLEHAUL_API_KEY");
    }

    /** One call. Retries 429 (after Retry-After) and 502/503/504 (growing wait). */
    public function get(string $path, array $params = []): array
    {
        $url = self::API . $path . ($params ? "?" . http_build_query($params) : "");
        for ($attempt = 0; $attempt < $this->maxTries; $attempt++) {
            $retryAfter = 0.0;
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 60,
                CURLOPT_HTTPHEADER => ["X-Api-Key: " . $this->apiKey],
                CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$retryAfter): int {
                    if (stripos($line, "retry-after:") === 0) {
                        $retryAfter = (float) trim(substr($line, 12));
                    }
                    return strlen($line);
                },
            ]);
            $raw = curl_exec($ch);
            if ($raw === false) {
                throw new RuntimeException(curl_error($ch));
            }
            $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
            if (in_array($status, self::RETRY, true) && $attempt < $this->maxTries - 1) {
                usleep((int) (($retryAfter ?: 2 ** $attempt) * 1_000_000));
                continue;
            }
            $body = json_decode($raw, true, flags: JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
            if ($status >= 400) {
                throw new HandleHaulException($status, $body["error"]["code"] ?? null, $body["error"]["message"] ?? "");
            }
            $this->credits += $body["meta"]["credits_charged"] ?? 0;
            return $body;
        }
        throw new HandleHaulException(429, "rate_limited", "still limited after retries");
    }

    /** Every row of a list endpoint, one page (one call) at a time. Stop iterating to stop paying. */
    public function paginate(string $path, array $params = [], int $maxPages = 10): Generator
    {
        for ($page = 0; $page < $maxPages; $page++) {
            $body = $this->get($path, $params);
            yield from $body["data"];
            if (!$body["pagination"]["has_more"]) {
                return;
            }
            $params["cursor"] = $body["pagination"]["next_cursor"];
        }
    }
}

if (realpath($argv[0] ?? "") === __FILE__) {
    $hh = new HandleHaul();
    $post = $hh->get("/tiktok/posts/7300000000000000123")["data"];
    echo $post["counts"]["views"], " views, ", $post["counts"]["likes"], " likes\n";
    foreach ($hh->paginate("/tiktok/posts/7300000000000000123/comments", [], 2) as $c) {
        echo $c["like_count"], " ", $c["text"], "\n";
    }
    try {
        $hh->get("/instagram/users/private_demo/followers");
    } catch (HandleHaulException $e) {
        echo "expected error: ", $e->errorCode, "\n";
    }
    echo "credits used: ", $hh->credits, "\n";
}
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 PHP

Each page below has a complete PHP program for one route, the parameters, a sample response and what it costs. The link opens the PHP 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

PHP: questions

Is there a PHP SDK?
Not yet: the official SDKs are for Node.js and Python. The API is plain JSON over HTTPS with one header, so the class above (or Guzzle, if you already use it) covers every route.
How do I read Retry-After in PHP cURL?
Pass a CURLOPT_HEADERFUNCTION callback that captures the retry-after line, then usleep() that many seconds before the next try, as in the class above.
Can I run this from a cron job?
Yes. A cron script that pages newest-first lists only as deep as it needs costs one credit per page. Polling once a minute or less often gets live answers; identical calls inside the cache window are free.

Build it in PHP

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.