# Instagram data API in Python and JavaScript

> Call the HandleHaul Instagram data API from Python with requests or from JavaScript and TypeScript with fetch: one X-Api-Key header, JSON responses, cursor pagination. Copy-paste code for profiles, followers, following, paging and retries.

**Short answer:** from Python, call `requests.get("https://api.handlehaul.com/v1/users/{user}/following", headers={"X-Api-Key": key})`; from JavaScript or TypeScript, `fetch` the same URL with the same header. Every response is JSON shaped `{ data, pagination?, meta }`. To read more rows, pass `pagination.next_cursor` back as `?cursor=` until it is `null`.

> **Official SDKs:** `npm install handlehaul` for JavaScript and TypeScript, `pip install handlehaul` for Python (source on GitHub: [handlehaul-js](https://github.com/handlehaul/handlehaul-js) and [handlehaul-python](https://github.com/handlehaul/handlehaul-python)). The plain HTTP examples on this page work the same with or without them.

> **Definition:** the HandleHaul API is a REST API for public Instagram data: profiles, followers and following in newest-first order, posts, reels, stories, comments, hashtags and more. You authenticate with one API key in the `X-Api-Key` header; `kd_test_` keys return sample data at no cost and `kd_live_` keys return real data.

## Setup

Keep the key in an environment variable, never in code. Start with a test key from the [dashboard](/dashboard#keys): it returns sample data in the live schema, so the same code works when you switch to a live key ([Sandbox](/docs/sandbox)).

| | Python | JavaScript / TypeScript |
|---|---|---|
| Runtime | Python 3.8+ | Node.js 18+, Deno, Bun, Cloudflare Workers |
| HTTP client | `pip install requests` | Built-in `fetch` |
| Key | `os.environ["HANDLEHAUL_API_KEY"]` | `process.env.HANDLEHAUL_API_KEY` |
| Types | Plain dicts | Generate from [openapi.json](https://api.handlehaul.com/openapi.json) |

## First call: a profile

```bash
curl "https://api.handlehaul.com/v1/users/by-username/natgeo" \
  -H "X-Api-Key: $HANDLEHAUL_API_KEY"
```

```python
import os, requests

r = requests.get(
    "https://api.handlehaul.com/v1/users/by-username/natgeo",
    headers={"X-Api-Key": os.environ["HANDLEHAUL_API_KEY"]},
    timeout=30,
)
r.raise_for_status()
user = r.json()["data"]
print(user["id"], user["username"], user["counts"])
```

```javascript
const res = await fetch("https://api.handlehaul.com/v1/users/by-username/natgeo", {
  headers: { "X-Api-Key": process.env.HANDLEHAUL_API_KEY },
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
console.log(body.data.id, body.data.username, body.data.counts);
```

```php
$ch = curl_init("https://api.handlehaul.com/v1/users/by-username/natgeo");
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => ["X-Api-Key: " . getenv("HANDLEHAUL_API_KEY")],
    CURLOPT_RETURNTRANSFER => true,
]);
$body = json_decode(curl_exec($ch), true);
print_r($body["data"]);
```

```go
req, _ := http.NewRequest("GET", "https://api.handlehaul.com/v1/users/by-username/natgeo", nil)
req.Header.Set("X-Api-Key", os.Getenv("HANDLEHAUL_API_KEY"))
res, err := http.DefaultClient.Do(req)
if err != nil {
    log.Fatal(err)
}
defer res.Body.Close()
var body map[string]any
json.NewDecoder(res.Body).Decode(&body)
fmt.Println(body["data"])
```

Store `data.id`. Later calls that take `{user}` accept the numeric id, which skips the 1-credit username lookup.

## Paging through a list

Lists such as followers and following are newest first and paged with an opaque cursor. Each page is one billed call, so stop as soon as you have what you need.

```python
def pages(path, max_pages=10):
    cursor = None
    for _ in range(max_pages):
        r = requests.get(f"https://api.handlehaul.com/v1{path}", params={"cursor": cursor} if cursor else {},
                         headers={"X-Api-Key": os.environ["HANDLEHAUL_API_KEY"]}, timeout=30)
        r.raise_for_status()
        body = r.json()
        yield from body["data"]
        cursor = body["pagination"]["next_cursor"]
        if not cursor:
            break

for row in pages("/users/natgeo/followers", max_pages=2):
    print(row["position"], row["username"])
```

```javascript
async function* pages(path, maxPages = 10) {
  let cursor = null;
  for (let i = 0; i < maxPages; i++) {
    const qs = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
    const res = await fetch(`https://api.handlehaul.com/v1${path}${qs}`, {
      headers: { "X-Api-Key": process.env.HANDLEHAUL_API_KEY },
    });
    const body = await res.json();
    if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
    yield* body.data;
    cursor = body.pagination.next_cursor;
    if (!cursor) break;
  }
}

for await (const row of pages("/users/natgeo/following", 1)) console.log(row.position, row.username);
```

## Retries

Retry only what can succeed later: `429` (wait for the `Retry-After` header, in seconds) and `502`, `503`, `504` (back off). Never retry `401`, `402`, `403` or `404`. Failed calls are not billed, so a retry costs nothing extra until it succeeds.

```python
import time

def get(path, tries=3):
    for attempt in range(tries):
        r = requests.get(f"https://api.handlehaul.com/v1{path}", headers={"X-Api-Key": os.environ["HANDLEHAUL_API_KEY"]}, timeout=30)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "1")))
        elif r.status_code in (502, 503, 504):
            time.sleep(2 ** attempt)
        else:
            r.raise_for_status()
            return r.json()
    r.raise_for_status()
```

```javascript
async function get(path, tries = 3) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`https://api.handlehaul.com/v1${path}`, { headers: { "X-Api-Key": process.env.HANDLEHAUL_API_KEY } });
    const retry = res.status === 429 || [502, 503, 504].includes(res.status);
    if (!retry || attempt === tries - 1) {
      const body = await res.json();
      if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
      return body;
    }
    const wait = res.status === 429 ? Number(res.headers.get("Retry-After") ?? 1) : 2 ** attempt;
    await new Promise((r) => setTimeout(r, wait * 1000));
  }
}
```

All error codes: [Errors](/docs/errors). Speed per pack: [Rate limits](/docs/rate-limits).

## TypeScript types

Generate types for every endpoint from the OpenAPI 3.1 spec, for example with `openapi-typescript`:

```bash
npx openapi-typescript https://api.handlehaul.com/openapi.json -o handlehaul-api.d.ts
```

Any OpenAPI generator works the same way for other languages. AI coding tools can read [AGENTS.md](https://api.handlehaul.com/AGENTS.md) for the rules and endpoints ([Build with AI tools](/docs/build-with-ai)).

## Keep the key on the server

The API accepts browser requests for quick tests, but a live key in browser or mobile code is visible to every user, who could spend your credits. Call the API from your backend (a Python view, a Node.js route, a serverless function) and send only the result to the browser.

## FAQ

### Is there an official HandleHaul SDK for Python or JavaScript?
Yes: `npm install handlehaul` for JavaScript and TypeScript and `pip install handlehaul` for Python ([guide](/docs/instagram-api-python-javascript); source: [handlehaul-js](https://github.com/handlehaul/handlehaul-js) and [handlehaul-python](https://github.com/handlehaul/handlehaul-python)). The API is also plain HTTPS and JSON with one header, so a few lines of `fetch` or `requests` work just as well, and the [OpenAPI spec](https://api.handlehaul.com/openapi.json) generates a typed client in any language.

### How do I call the Instagram followers API from Python?
Send GET https://api.handlehaul.com/v1/users/{user}/followers with requests and the header X-Api-Key. The response's data array holds 25 followers, newest first; pass pagination.next_cursor as ?cursor= for the next page.

### How do I call the Instagram following API from JavaScript?
fetch("https://api.handlehaul.com/v1/users/{user}/following", { headers: { "X-Api-Key": key } }) from server-side code. The response holds about 200 accounts a page, newest first, for 1 credit.

### Can I call the API from the browser?
Only with a kd_test_ key, for experiments. A live key in browser code is visible to every visitor, and the response carries a meta.warning when that happens. Use a server route for real traffic.
