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.envor 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()readsRetry-Afterfrom the response headers throughCURLOPT_HEADERFUNCTION, sleeps that long on429, and retries502,503and504with a growing wait. Those answers are free.paginate()returns aGenerator: rows arrive page by page, and abreakin yourforeachstops the next call. Errors throwHandleHaulExceptionwithstatusanderrorCode.- 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";
}
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.
| 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 |
PHP: questions
Is there a PHP SDK?
How do I read Retry-After in PHP cURL?
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?
Related
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).
Read more →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 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 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.