> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Download an Instagram reel in Python

> Python code that takes a public Instagram reel link, gets the MP4 through the Importly API and saves it, with polling, error handling and the response you get back.

Your users paste an Instagram reel link and your Python backend needs the video. Instagram's own API only covers accounts that connect to your app, and anonymous requests from servers hit a login wall. This sends the public reel link to Importly and saves the finished MP4. It needs only `requests`.

## The code

```python download_reel.py theme={null}
import os
import sys
import time

import requests

API = "https://api.importly.io"
HEADERS = {"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"}


class ImportlyError(Exception):
    pass


def download_reel(reel_url: str, output_path: str) -> dict:
    # 1. Start the import. It returns a jobId right away.
    start = requests.post(f"{API}/import", headers=HEADERS, json={"url": reel_url}, timeout=30)
    started = start.json()
    if not start.ok or not started.get("success"):
        # Rejected up front: bad link, bad key, low balance or rate limit
        raise ImportlyError(f"{started.get('code')}: {started.get('error')}")

    # 2. Poll until the job is done.
    job_id = started["data"]["jobId"]
    while True:
        time.sleep(3)
        res = requests.get(f"{API}/import/status", headers=HEADERS, params={"id": job_id}, timeout=30)
        job = res.json()["data"]
        if job["status"] not in ("queued", "running"):
            break

    if job["status"] == "failed":
        # e.g. VIDEO_PRIVATE or AUTH_REQUIRED. Failed imports aren't charged.
        raise ImportlyError(f"{job.get('code')}: {job.get('message')}")

    # 3. Save the file. mediaUrl is a signed link, valid for 7 days.
    with requests.get(job["result"]["mediaUrl"], stream=True, timeout=60) as file:
        file.raise_for_status()
        with open(output_path, "wb") as out:
            for chunk in file.iter_content(chunk_size=1 << 20):
                out.write(chunk)
    return job["result"]


if __name__ == "__main__":
    result = download_reel(sys.argv[1], "reel.mp4")
    print(f"Saved {result['title']!r} ({result['duration']}s) for ${result['totalCostInDollars']}")
```

```bash theme={null}
pip install requests
IMPORTLY_API_KEY=your_api_key python download_reel.py "https://www.instagram.com/reel/<id>/"
```

`/reel/` and `/p/` links both work.

## What comes back

The finished job from `GET /import/status`:

```json theme={null}
{
  "success": true,
  "data": {
    "jobId": "a824760e-ece1-4415-8838-ce2a7785ea6b",
    "status": "completed",
    "result": {
      "mediaUrl": "https://storage.example.com/imports/a824760e-…/reel.mp4?X-Amz-…",
      "title": "Video by example_account",
      "duration": 22,
      "fileSizeBytes": 3104512,
      "costInDollars": 0.01,
      "totalCostInDollars": 0.01
    }
  }
}
```

Set `includeVideo: False` in the request body for the audio only. All options are in [Downloads](/docs/features/downloads.md).

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `400` `INVALID_URL` | Show the user the link isn't a reel |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Add credits; nothing was charged |
| Start request | HTTP `429` | Wait `retryAfter` seconds and retry |
| Status | `status: "failed"`, `code: "VIDEO_PRIVATE"` or `"AUTH_REQUIRED"` | The reel is private or needs a login; tell the user |

Importly fetches what's public: private accounts, close-friends stories and anything behind a login fail and aren't charged. Only download reels your users have the right to use. See [Supported sites](/docs/features/supported-sites.md) and [Error handling](/docs/error-handling.md).

## In production

* In a web app, don't block a request on the loop. Pass `webhookUrl` and save the file when Importly calls you back ([Webhooks](/docs/webhooks.md)); the [Python (FastAPI) recipe](/docs/integrations/python.md) shows the endpoints.
* Copy the file somewhere permanent, or set `store: true` to have it land in your own bucket ([recipe](/docs/integrations/save-to-bucket.md)).

> [!NOTE]
>
> Downloads cost $0.002 per MB, with a $0.01 minimum. Try it free, no card required. See [Pricing & credits](/docs/billing.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.