DEV Community

Louis Terrell
Louis Terrell

Posted on

Download Instagram reels with audio in Python: a small script with an API

Say you have a list of public Instagram reel links and you want the MP4 files on disk, with sound, plus the caption and the song for each one. This post builds a small Python script that does that with a hosted API, and covers the parts that usually trip people up: silent files, links that expire, carousels with several items, and errors that come back with HTTP 200.

Disclosure: I work on APIWren, which makes the API used here. The approach (call an endpoint, stream the CDN file, handle expiry) applies to any similar service.

What the API returns

The Instagram Reels Downloader API has one endpoint, GET /reel. You send the link of a public reel, video post or carousel (or just its shortcode) and get back JSON like this, trimmed:

{
  "data": {
    "shortcode": "DaI91choaNb",
    "type": "video",
    "video_url": "https://instagram.fhan14-5.fna.fbcdn.net/.../AQOm4U6N.mp4?...",
    "video_expires_at": "2026-12-08T22:49:46.000Z",
    "duration": 17.786,
    "has_audio": true,
    "music": { "title": "Dust", "artist": "Hans Zimmer" },
    "items": [
      { "type": "video", "video_url": "https://...mp4?...", "image_url": "https://...jpg?...", "expires_at": "2026-12-08T22:49:46.000Z" }
    ]
  },
  "meta": { "cached": false, "fetched_at": "2026-12-04T11:02:17.412Z" }
}
Enter fullscreen mode Exit fullscreen mode

Three fields matter most:

  • video_url is one MP4 with H.264 video and AAC audio together, up to 720p.
  • video_expires_at is when Instagram's CDN link stops working, usually 1 to 4 days out. Save the file before then.
  • items lists every video and image of a carousel, each with its own link. For a single reel it has one entry.

The full field list is in the GET /reel reference.

Why some downloaded reels have no sound

Instagram keeps a reel in two forms: a single MP4 with audio, and separate video-only and audio-only streams for adaptive playback. A downloader that grabs the best video stream from the second set saves a silent file. Reels that use licensed music are another trap, because Instagram's embed page leaves the video out for them, so tools that only read the embed page get nothing. There's a longer write-up in how to download Instagram reels with audio. The short version for this script: use video_url as it is and you get the sound.

Setup

You need Python 3.9 or later, requests, and a RapidAPI key. The free plan covers 1,000 requests a month, and one reel link is one request.

pip install requests
export RAPIDAPI_KEY="your key from RapidAPI"
Enter fullscreen mode Exit fullscreen mode

The script

import os
import sys
import time

import requests

HOST = "instagram-reels-downloader-videos-carousels-music-reels.p.rapidapi.com"
HEADERS = {
    "X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"],
    "X-RapidAPI-Host": HOST,
}


def get_post(link, retries=3):
    """Return the 'data' object for one public reel, video post or carousel."""
    for attempt in range(retries):
        resp = requests.get(
            f"https://{HOST}/reel", params={"url": link}, headers=HEADERS, timeout=30
        )
        if resp.status_code == 502:  # upstream_failed: worth a retry
            time.sleep(3 * (attempt + 1))
            continue
        resp.raise_for_status()
        body = resp.json()
        if body.get("success") is False:  # not_found, restricted, invalid_input
            err = body["error"]
            raise ValueError(f"{link}: {err['code']} ({err['message']})")
        return body["data"]
    raise RuntimeError(f"{link}: upstream kept failing, try again later")


def save(url, path):
    """Stream a CDN file to disk instead of holding it in memory."""
    with requests.get(url, stream=True, timeout=60) as r:
        r.raise_for_status()
        with open(path, "wb") as f:
            for chunk in r.iter_content(chunk_size=1 << 16):
                f.write(chunk)


def download(link, out_dir="reels"):
    os.makedirs(out_dir, exist_ok=True)
    post = get_post(link)
    code = post["shortcode"]
    saved = []
    for i, item in enumerate(post["items"], start=1):
        if item["type"] == "video":
            path = os.path.join(out_dir, f"{code}_{i}.mp4")
            save(item["video_url"], path)
        else:
            path = os.path.join(out_dir, f"{code}_{i}.jpg")
            save(item["image_url"], path)
        saved.append(path)
    print(f"{code}: {len(saved)} file(s), music={post.get('music')}, links expire {post.get('video_expires_at')}")
    return saved


if __name__ == "__main__":
    links = sys.argv[1:] or [line.strip() for line in sys.stdin if line.strip()]
    for link in links:
        try:
            download(link)
        except (ValueError, RuntimeError) as e:
            print("skipped", e, file=sys.stderr)
        time.sleep(1)  # stay well inside your plan's rate limit
Enter fullscreen mode Exit fullscreen mode

Run it with links as arguments, or pipe a file with one link per line:

python reels.py https://www.instagram.com/reel/DaI91choaNb/
python reels.py < links.txt
Enter fullscreen mode Exit fullscreen mode

A few details worth knowing

Errors come back as HTTP 200. A private, deleted or missing post returns "success": false with error.code set to not_found. An age or region gated post returns restricted, and bad input returns invalid_input. If you only check the status code you'll treat these as successes, so the script checks success first. Only upstream_failed uses a real error status (502), and that one is worth retrying after a few seconds.

Stream big files. requests.get(url).content holds the whole video in memory. With stream=True and iter_content the file goes to disk in chunks, which matters once you batch a few hundred reels.

Save early. The CDN links are signed and expire. If you store video_url in a database to download later, it may be dead by then. Download right away, or keep the reel link and call the API again when you need a fresh one. Repeat calls for the same post within an hour come from cache.

Only public posts work. Private accounts, stories and anything Instagram doesn't show publicly can't be read, and you need the post link or shortcode. There's no profile feed or hashtag endpoint.

Need just the audio? The track is already inside the MP4, so ffmpeg can copy it out without re-encoding:

ffmpeg -i DaI91choaNb_1.mp4 -vn -c:a copy DaI91choaNb.m4a
Enter fullscreen mode Exit fullscreen mode

When a library fits better

If you're archiving your own account, or you only need a handful of reels now and then, a local tool like Instaloader or yt-dlp may be enough. They run into rate limits and 401 or 429 errors at volume, which is when a hosted endpoint starts to make sense. The Instaloader alternatives guide goes through those errors and the trade-offs, and this comparison of Instagram downloader APIs lines up free tiers and prices across several providers if you want to shop around.

If you want to check a link before writing any code, the free Instagram reel downloader runs on the same endpoint in the browser.

One more thing

Reels belong to the people who made them, and the music is licensed to Instagram. Downloading for research, archiving your own posts or feeding a transcription pipeline is one thing. Reposting someone's reel usually needs their permission, so ask and credit them.

Top comments (0)