Guide

How to download Instagram Reels, photos and carousels with an API in Python (no login)

A step-by-step walkthrough: one GET request returns direct links to videos and photos from a public post, with no account, cookies or proxies. The Python, JS and PHP code was tested on live links.

9 min read

Why instaloader and homemade scrapers keep breaking

Instagram has moved almost everything behind a login. Anonymous requests from server IPs get rejected quickly, and libraries that work through your own account come with their own set of problems. The symptoms are familiar:

  • 401 Unauthorized - "Please wait a few minutes before you try again.", the instaloader classic: you have not downloaded anything yet and Instagram already asks you to wait;
  • 429 and “Too many requests” after a few dozen calls from one address;
  • checkpoint_required, challenges, SMS or email confirmation, which means the account looked suspicious;
  • a temporary or permanent ban on the account you ran the script with.

The usual cure is rotating accounts, proxies and sessions, which is a side project that needs repairs after every Instagram change. If all you need is media files from public posts, not profile data, it is simpler to hand the job to an API. Below is a working Python example with no login, no cookies and no proxies.

What the /api/v1/instagram endpoint supports

GET /api/v1/instagram takes a link to a public post and returns JSON with direct file URLs:

  • Reels, links like instagram.com/reel/…;
  • regular posts, instagram.com/p/…, a single photo or video;
  • carousels, several slides with photos and videos mixed.

Private accounts are not available and the API answers 403 for them. Stories and highlights are not listed in the API catalog, so do not count on them. You can even pass the link together with “Share” text, and the server will pull the Instagram URL out of the string. There is one parameter, url; the optional type defaults to media, which covers both photos and videos. If you do not know the platform in advance, /api/v1/auto?url=… detects it for you and is billed as that platform.

Step 1. Your first request

Grab a key in your account and send it in the X-API-Key header:

bash
curl -G "https://api.interapi.dev/api/v1/instagram" \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode "url=https://www.instagram.com/reel/DYluJYONqX6/"

A Reel comes back like this (URLs shortened):

json
{
  "status": "success",
  "platform": "InterAPI",
  "title": "",
  "media": [
    { "type": "video", "quality": null, "url": "https://scontent.cdninstagram.com/o1/v/t2/…", "download_url": "https://dl.snapcdn.app/saveinsta?token=…" },
    { "type": "photo", "quality": null, "url": "https://scontent.cdninstagram.com/v/t51.71878-15/….jpg", "download_url": "https://dl.snapcdn.app/saveinsta?token=…" }
  ],
  "video_url": "https://scontent.cdninstagram.com/o1/v/t2/…",
  "video_hd_url": "https://scontent.cdninstagram.com/o1/v/t2/…",
  "thumbnail": "https://scontent.cdninstagram.com/v/t51.71878-15/….jpg",
  "duration_ms": 863
}

What matters here:

  • media is the array of files. Each item has a type (video or photo), a direct url and a download_url, a variant served as an attachment. Both work; the code below uses url.
  • A Reel usually has two items in media: the video and its cover. The main video is duplicated in video_url and video_hd_url, the cover in thumbnail.
  • title, description and author currently come back empty for Instagram: the API does not return the post caption.

In a test carousel of five photos, media held not 5 but 45 items. Every slide is listed in nine sizes, from 1440x1440 down to 150x150, and the size sits in the quality field:

json
{ "type": "photo", "quality": "1440x1440", "url": ".../651110129_17959028681925270_..._n.jpg?stp=dst-jpg_e35_tt6&..." }
{ "type": "photo", "quality": "1080x1080", "url": ".../651110129_17959028681925270_..._n.jpg?stp=dst-jpg_e35_s1080x1080_tt6&..." }
{ "type": "photo", "quality": "750x750",   "url": ".../651110129_17959028681925270_..._n.jpg?stp=...&..." }
... six more sizes down to 150x150

All variants of one slide share the same CDN path and differ only in the query string after ?. Download everything blindly and you end up with 45 files instead of 5. So we group items by urlparse(url).path and keep the largest one by quality. Videos have an empty quality and simply stay as the only variant.

Step 2. Download everything in Python

bash
pip install requests aiohttp
python
import os
import re
import time
from pathlib import Path
from urllib.parse import urlparse

import requests

API = "https://api.interapi.dev"
API_KEY = os.environ["INTERAPI_KEY"]

CONTENT_TYPES = {
    "video/mp4": ".mp4",
    "image/jpeg": ".jpg",
    "image/webp": ".webp",
    "image/png": ".png",
}


class ApiError(Exception):
    def __init__(self, status: int, detail: str):
        super().__init__(f"{status}: {detail}")
        self.status = status


def fetch_post(url: str, retries: int = 4) -> dict:
    """Call /api/v1/instagram. Retries 429 and 5xx (5xx is free), fails fast on other 4xx."""
    for attempt in range(retries):
        r = requests.get(
            f"{API}/api/v1/instagram",
            params={"url": url},
            headers={"X-API-Key": API_KEY},
            timeout=60,
        )
        if r.status_code == 200:
            return r.json()

        retryable = r.status_code == 429 or r.status_code >= 500
        wait = int(r.headers.get("Retry-After") or 2 ** (attempt + 1))
        if retryable and attempt < retries - 1 and wait <= 60:
            time.sleep(wait)  # short upstream hiccup: wait and try again
            continue

        try:
            detail = r.json().get("detail", r.text)
        except ValueError:
            detail = r.text[:200]
        raise ApiError(r.status_code, str(detail))
    raise ApiError(0, "retries exhausted")


def resolution(item: dict) -> int:
    m = re.match(r"(\d+)x(\d+)", item.get("quality") or "")
    return int(m[1]) * int(m[2]) if m else 0


def unique_files(media: list[dict]) -> list[dict]:
    """One entry per slide: the API lists every photo in several sizes under the same path."""
    best: dict[str, dict] = {}
    for item in media:
        key = urlparse(item["url"]).path
        if key not in best or resolution(item) > resolution(best[key]):
            best[key] = item
    return list(best.values())


def shortcode(post_url: str) -> str:
    m = re.search(r"instagram\.com/(?:[\w.]+/)?(?:p|reel|reels|tv)/([\w-]+)", post_url)
    return m.group(1) if m else "post"


def save(item: dict, dest: Path) -> Path:
    # The CDN link is public: do NOT send your API key there, so no shared session headers.
    with requests.get(item["url"], stream=True, timeout=(10, 60)) as r:
        r.raise_for_status()
        ctype = r.headers.get("Content-Type", "").split(";")[0]
        ext = CONTENT_TYPES.get(ctype, ".mp4" if item["type"] == "video" else ".jpg")
        path = dest.with_suffix(ext)
        tmp = path.with_name(path.name + ".part")
        with open(tmp, "wb") as f:
            for chunk in r.iter_content(chunk_size=1 << 20):
                f.write(chunk)
    tmp.replace(path)
    return path


def download_post(post_url: str, out_dir: str = "downloads") -> list[Path]:
    data = fetch_post(post_url)
    files = unique_files(data["media"])
    videos = [f for f in files if f["type"] == "video"]
    photos = [f for f in files if f["type"] == "photo"]
    if videos and len(photos) <= 1:  # a Reel comes as [video, cover]: the lone photo is just the cover
        files = videos
    Path(out_dir).mkdir(exist_ok=True)
    code = shortcode(post_url)
    return [save(f, Path(out_dir) / f"{code}_{i:02d}") for i, f in enumerate(files, 1)]


# usage
print(download_post("https://www.instagram.com/reel/DYluJYONqX6/"))

A few things worth noticing in the code:

  • The key never reaches the CDN. Files are fetched with a plain requests.get, not through a session carrying X-API-Key. The link is public, and there is no reason to hand your key to someone else’s server.
  • The extension comes from Content-Type, because video URLs have no extension.
  • File names are built from the post shortcode and a running number, like DYluJYONqX6_01.mp4, so a re-run does not pile up duplicates.
  • Download right away. CDN links are short-lived (they include an oe parameter with the expiry time), so storing them for days is pointless.
  • If a post has one video and at most one photo, the photo is treated as the cover and skipped. For a carousel made of videos plus a single photo, call unique_files directly.

Errors, retries and rate limits

Errors always arrive as JSON shaped like {"detail": "...", "request_id": "..."}. Log the request_id; it makes support conversations much easier.

CodeMeaningWhat to do
400Invalid linkDo not retry, check the URL
401Missing or invalid keyCheck the X-API-Key header
402Not enough creditsTop up the balance
403Post is closed (private account)Skip the link
404Post deleted or not foundSkip the link
429Rate limitRead Retry-After; wait out a short delay, not a long one
5xxFailure on the service sideRetry with exponential backoff; no credits are charged

4xx responses cost at most 1 credit and 5xx are free, which is why fetch_post retries only 429 and 5xx. There is a catch with 429: until your first top-up a limit of 30 requests per hour applies, and Retry-After can be long in that case. The code above waits at most a minute and otherwise raises, instead of parking a worker for an hour. Every successful response also carries X-Balance-Remaining and X-Request-Cost headers, handy for tracking your balance.

Batches: an async version with aiohttp

For hundreds of posts, run requests in parallel. The semaphore caps concurrent tasks, and one bad link does not take the rest down (return_exceptions=True):

python
import asyncio
import os
import re
from pathlib import Path
from urllib.parse import urlparse

import aiohttp

API = "https://api.interapi.dev"
API_KEY = os.environ["INTERAPI_KEY"]
EXT = {"video/mp4": ".mp4", "image/jpeg": ".jpg", "image/webp": ".webp", "image/png": ".png"}


def pick_files(media: list[dict]) -> list[dict]:
    """One best file per slide (same URL path = same slide in different sizes)."""
    def area(m):
        s = re.match(r"(\d+)x(\d+)", m.get("quality") or "")
        return int(s[1]) * int(s[2]) if s else 0

    best: dict[str, dict] = {}
    for m in media:
        key = urlparse(m["url"]).path
        if key not in best or area(m) > area(best[key]):
            best[key] = m
    files = list(best.values())
    videos = [f for f in files if f["type"] == "video"]
    photos = [f for f in files if f["type"] == "photo"]
    return videos if videos and len(photos) <= 1 else files


async def fetch_post(api: aiohttp.ClientSession, url: str, retries: int = 4) -> dict:
    for attempt in range(retries):
        async with api.get(f"{API}/api/v1/instagram", params={"url": url}) as r:
            if r.status == 200:
                return await r.json()
            wait = int(r.headers.get("Retry-After") or 2 ** (attempt + 1))
            if (r.status == 429 or r.status >= 500) and attempt < retries - 1 and wait <= 60:
                await asyncio.sleep(wait)
                continue
            raise RuntimeError(f"{url}: HTTP {r.status} {(await r.text())[:200]}")
    raise RuntimeError(f"{url}: retries exhausted")


async def save(cdn: aiohttp.ClientSession, item: dict, dest: Path) -> Path:
    async with cdn.get(item["url"]) as r:
        r.raise_for_status()
        ext = EXT.get(r.content_type, ".mp4" if item["type"] == "video" else ".jpg")
        path = dest.with_suffix(ext)
        with open(path, "wb") as f:
            async for chunk in r.content.iter_chunked(1 << 20):
                f.write(chunk)
    return path


async def process(api, cdn, sem, url: str, out: Path) -> list[Path]:
    async with sem:  # at most N posts in flight
        data = await fetch_post(api, url)
        code = re.search(r"/(?:p|reel|reels|tv)/([\w-]+)", url)[1]
        files = pick_files(data["media"])
        return [await save(cdn, f, out / f"{code}_{i:02d}") for i, f in enumerate(files, 1)]


async def main(urls: list[str]) -> None:
    out = Path("downloads")
    out.mkdir(exist_ok=True)
    sem = asyncio.Semaphore(5)
    timeout = aiohttp.ClientTimeout(total=120)
    async with aiohttp.ClientSession(headers={"X-API-Key": API_KEY}, timeout=timeout) as api, \
            aiohttp.ClientSession(timeout=timeout) as cdn:  # separate session: no API key for the CDN
        results = await asyncio.gather(*(process(api, cdn, sem, u, out) for u in urls), return_exceptions=True)
    for url, res in zip(urls, results):
        print(url, "->", res if isinstance(res, Exception) else [p.name for p in res])


if __name__ == "__main__":
    import sys

    asyncio.run(main(sys.argv[1:]))

Run it with python ig_async.py URL1 URL2 …. Start with 3–5 concurrent tasks and raise the number until you see 429s.

The same thing in JavaScript and PHP

The protocol is identical: a GET request, an X-API-Key header and JSON in the response. Node.js 18+ (fetch is built in):

javascript
const API = "https://api.interapi.dev";

async function getPost(postUrl) {
  const res = await fetch(`${API}/api/v1/instagram?url=${encodeURIComponent(postUrl)}`, {
    headers: { "X-API-Key": process.env.INTERAPI_KEY },
  });
  if (!res.ok) {
    const err = await res.json();
    throw new Error(`${res.status}: ${err.detail}`);
  }
  return res.json();
}

const data = await getPost("https://www.instagram.com/reel/DYluJYONqX6/");
const video = data.media.find((m) => m.type === "video");
console.log(video?.url);

PHP with the cURL extension:

php
<?php
$query = http_build_query(['url' => 'https://www.instagram.com/reel/DYluJYONqX6/']);
$ch = curl_init("https://api.interapi.dev/api/v1/instagram?$query");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['X-API-Key: ' . getenv('INTERAPI_KEY')],
    CURLOPT_TIMEOUT        => 60,
]);
$body   = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode($body, true);
if ($status !== 200) {
    exit("Error $status: " . ($data['detail'] ?? 'unknown') . "\n");
}
foreach ($data['media'] as $m) {
    echo $m['type'], ' ', $m['url'], "\n";
}

If you are building a Telegram bot, see the step-by-step guides in Python and in PHP. And for YouTube the pain is different: yt-dlp on a server runs into the “not a bot” check, covered in a separate guide.

What it costs and how to avoid paying twice

A successful Instagram request costs 6 credits, and a carousel with any number of slides is still one request. The 1,000 free credits you get at sign-up cover about 166 posts (1000 / 6). The Start package gives 60,000 credits for $5, roughly 10,000 posts; credits never expire and there is no subscription. Current packages live on the pricing page.

The cheapest optimization is your own cache:

  • use the post shortcode as the key and store paths to files you already downloaded (disk, S3) or a Telegram file_id as the value;
  • cache files, not CDN links, because links go stale;
  • check the cache before calling the API, so the same post reposted in a chat does not cost 6 credits a second time.

Try it

Sign up, get 1,000 credits and run the code above on your own links: create an account and a key. Parameters, examples and a browser test live in the Instagram API docs, and prices are on the pricing page.

FAQ

Do I need an Instagram login or cookies?

No. The request carries your InterAPI key in the X-API-Key header, and no Instagram account is involved, so there is nothing to get banned. This works for public posts only.

Can I download content from a private account?

No. For private accounts the API answers 403, which costs at most 1 credit. Stories and highlights are not listed in the API catalog.

How do I download every slide of a carousel?

Each slide arrives in the media array in several sizes under one CDN path. Group the items by URL path (urlparse(url).path) and from each group keep the variant with the largest quality, for example 1440x1440.

How much does it cost to download Reels and photos?

A successful /api/v1/instagram request costs 6 credits, and a carousel is still one request. The 1,000 free sign-up credits cover about 166 posts. 5xx responses are free and 4xx cost at most 1 credit.

What should I do about the instaloader “Please wait a few minutes” error?

It is an Instagram throttle on your IP or account, and there is no stable way around it: pauses only help for a while. If you only need media files from public posts, move downloading to an API.

More guides

All guides