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

# See a video's download options and cost before importing, in Python

> List every quality a video link can be downloaded at, each with its file type, size and price, then import the one you pick - so you (or your agent) spend only after seeing the cost.

Before you download a video link, you often want to know what you'll get and what it will cost: which resolutions are available, whether the file plays everywhere, and the price of each. Importly's [`POST /metadata`](/docs/endpoints/metadata) returns that list for any link, so you can show a user the choices, or let an agent pick, and only then import the one you want. A metadata call is \$0.003 and never downloads the media; you pay the download price only when you call [`POST /import`](/docs/features/downloads). The same recipe in Node is [Options and cost in Node](/docs/recipes/pick-quality-and-cost-node.md).

## The code

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

import requests

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


def run_job(path: str, body: dict, status_path: str) -> dict:
    """Start a job and poll its status endpoint until it finishes."""
    start = requests.post(f"{API}{path}", headers=HEADERS, json=body, timeout=30)
    started = start.json()
    if not start.ok or not started.get("success"):
        raise RuntimeError(f"{started.get('code')}: {started.get('error')}")

    job = started["data"]
    for _ in range(120):  # up to ~4 min; pass a webhookUrl instead in a queue worker
        if job["status"] not in ("queued", "running"):
            break
        time.sleep(2)
        res = requests.get(f"{API}{status_path}", headers=HEADERS, params={"id": job["jobId"]}, timeout=30)
        job = res.json()["data"]
    if job["status"] != "completed":
        raise RuntimeError(job.get("message") or f"Job {job['status']}")
    return job["result"]


def get_download_options(url: str) -> dict:
    """Return the list of download options for a link."""
    meta = run_job("/metadata", {"url": url}, "/metadata/status")
    options = meta.get("downloadOptions")
    if not options:  # e.g. a live stream that hasn't ended
        return {"title": meta.get("title"), "video": [], "audio": []}
    return {"title": meta.get("title"), "video": options["video"], "audio": options["audio"]}


def import_quality(url: str, video_quality: str) -> dict:
    """Download one chosen quality and return a link to the file."""
    result = run_job("/import", {"url": url, "videoQuality": video_quality}, "/import/status")
    return {"media_url": result["mediaUrl"], "cost": result["totalCostInDollars"], "filename": result["filename"]}


url = "https://www.youtube.com/watch?v=jNQXAC9IVRw"
options = get_download_options(url)

print(options["title"])
for o in options["video"]:
    cost = "size unknown" if o["estimatedCost"] is None else f"${o['estimatedCost']:.2f}"
    plays_everywhere = "" if o["h264"] else "  (re-encode for Safari/iOS with compatibleCodecs)"
    print(f"  {o['videoQuality']:<6} {o['ext']}  {o['width']}x{o['height']}  {cost}{plays_everywhere}")

# Pick the cheapest option at 720p or below, then import it.
affordable = [o for o in options["video"] if o["height"] <= 720 and o["estimatedCost"] is not None]
if affordable:
    choice = min(affordable, key=lambda o: o["estimatedCost"])
    file = import_quality(url, choice["videoQuality"])
    print(f"Imported {file['filename']} for ${file['cost']}: {file['media_url']}")
```

```bash theme={null}
pip install requests
IMPORTLY_API_KEY=your_api_key python options.py
```

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and keep it on the server.

## What comes back

The finished metadata job has a `downloadOptions` object with a `video` list and an `audio` list. Each row is one file you could import:

```json theme={null}
"downloadOptions": {
  "video": [
    { "videoQuality": "144p", "alsoMatches": ["lowest"], "width": 192, "height": 144, "fps": 15, "ext": "mp4", "h264": false, "estimatedBytes": 499526, "estimatedCost": 0.01 },
    { "videoQuality": "240p", "alsoMatches": ["360p", "480p", "720p", "1080p", "1440p", "2160p", "best"], "default": true, "width": 320, "height": 240, "ext": "mp4", "h264": false, "estimatedBytes": 538398, "estimatedCost": 0.01 }
  ],
  "audio": [
    { "audioQuality": "medium", "alsoMatches": ["high", "best"], "default": true, "bitrateKbps": 106, "estimatedBytes": 252182, "estimatedCost": 0.01 }
  ]
}
```

* Send a row's `videoQuality` to [`POST /import`](/docs/features/downloads) to get that file, or its `audioQuality` with `includeVideo: false` for audio only.
* `estimatedCost` is the price you'd pay for that import, in dollars. It's `null` when the source gives no size, so guard for it before sorting or displaying.
* Rows that return the same file are folded into one: the others are listed in `alsoMatches`, and `default: true` marks what you get if you import without naming a quality. So a video that tops out at 1080p lists it once with `1440p`, `2160p` and `best` beside it.
* `h264: false` means the file won't play in Safari, on iOS or in QuickTime as is. Send `compatibleCodecs: true` with the import to get an H.264 version where the source has one (usually a larger file, so the cost goes up).
* `video` is empty for audio-only sources such as podcasts, and `downloadOptions` is absent for a live stream that hasn't ended.

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `400` with an `error` | Not a valid link, or a playlist page (`PLAYLIST_NOT_SUPPORTED`). Ask for a single video link |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Add credits; nothing was charged |
| Start request | HTTP `429` | Wait `retryAfter` seconds and retry |
| Status | `status: "failed"`, e.g. `VIDEO_UNAVAILABLE` or `VIDEO_PRIVATE` | The video is gone or private; nothing was charged |

Every error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.md).

> [!NOTE]
>
> Listing the options costs \$0.003 per link, and status checks are free. You pay the download price only when you import. 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.