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

# Download an X (Twitter) video in Python

> Python code that checks an X or Twitter post has a video, gets the MP4 through the Importly API and saves it, with a cost cap and the errors to handle.

Your users paste X posts and your Python backend needs the video files. Without an X developer account there's no stable way to get them from a server: page scraping and unofficial endpoints break, and requests from cloud IPs get blocked or rate-limited. This sends the post link to Importly and saves the finished MP4. It needs Python 3.10 or later and `requests`. The [Node version](/docs/recipes/x-video-node.md) does the download in JavaScript.

Many pasted posts have only text or images. An import of one of those fails, but only after the post has been looked up, which can take a minute. So the script first asks for the post's length, which usually comes back much sooner, and only downloads when there's a video.

## The code

```python download_x_video.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):
    def __init__(self, code, message):
        super().__init__(f"{code}: {message}")
        self.code = code


def run_job(endpoint: str, body: dict, poll_every: float = 3) -> dict:
    # Start a job, then poll its status (free) until it finishes
    start = requests.post(f"{API}{endpoint}", headers=HEADERS, json=body, 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(started.get("code"), started.get("error"))

    job_id = started["data"]["jobId"]
    while True:
        time.sleep(poll_every)
        res = requests.get(f"{API}{endpoint}/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_UNAVAILABLE or AUTH_REQUIRED. Failed jobs aren't charged.
        raise ImportlyError(job.get("code"), job.get("message"))
    return job["result"]


def post_video_length(post_url: str) -> float | None:
    # $0.003: title, duration and thumbnail. A post with no video has duration None.
    return run_job("/metadata/basic", {"url": post_url}, poll_every=1.5)["duration"]


def download_x_video(post_url: str, output_path: str) -> dict:
    # videoQuality is a ceiling; maxCostDollars caps what one link can cost
    result = run_job("/import", {"url": post_url, "videoQuality": "720p", "maxCostDollars": 0.25})

    # mediaUrl is a signed link, valid for 7 days
    with requests.get(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 result


if __name__ == "__main__":
    url = sys.argv[1]
    length = post_video_length(url)
    if length is None:
        sys.exit("That post has no video in it.")
    if length > 600:
        sys.exit(f"That video is {length / 60:.0f} minutes long; the limit is 10.")

    result = download_x_video(url, "x-video.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_x_video.py "https://x.com/<user>/status/<id>"
```

Send the link as your users paste it: `x.com` and `twitter.com` post links both work, with or without tracking parameters such as `?s=20`. The link needs its `https://`; a bare `x.com/...` is rejected with `400` `INVALID_URL`.

## The length check

`POST /metadata/basic` returns four fields for \$0.003, and status checks are free:

```json theme={null}
{
  "success": true,
  "data": {
    "jobId": "7c3837a6-77f0-4ef8-926d-cab736e9569b",
    "status": "completed",
    "result": {
      "title": "jack - just setting up my twttr",
      "isLive": false,
      "duration": null,
      "thumbnail": null
    }
  }
}
```

A text-only post comes back with `duration: null`. A post with a video has its length in seconds (X reports fractions, such as `114.322`), so you can turn away long videos before you pay to download them. The 10-minute limit in the script is an example; set your own. Skip the check if your links always have a video, for example ones your own scraper collected from media posts. See [Metadata](/docs/features/metadata.md).

## 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-…/video.mp4?X-Amz-…",
      "title": "Example post text",
      "duration": 114.322,
      "fileSizeBytes": 11131301,
      "costInDollars": 0.022,
      "totalCostInDollars": 0.022
    }
  }
}
```

X serves each video in several bitrates. You don't pick one: Importly takes the best stream at or below `videoQuality` and gives you a single MP4. Set `includeVideo: false` for the audio only, or add `includeTranscript: true` for a timestamped transcript in the same job. 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 an X post |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Add credits; nothing was charged |
| Start request | HTTP `429` | Wait `retryAfter` seconds and retry |
| Length check | `duration` is `null` | The post has no video; tell the user |
| Status | `status: "failed"`, `code: "VIDEO_UNAVAILABLE"` | The post was deleted or has no video ("this post has no video in it"); tell the user |
| Status | `status: "failed"`, `code: "AUTH_REQUIRED"` or `"VIDEO_PRIVATE"` | Protected account or a post that needs a login; tell the user |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | The video costs more than `maxCostDollars`; raise the cap or lower `videoQuality` |

Importly fetches what's public. Every error has a `documentationUrl` with the fix. See [Media unavailable](/docs/errors/media-unavailable.md) and [Error handling](/docs/error-handling.md). Only download videos your users have the right to use.

## In production

* Don't make a web request wait on the polling loop. Run it in a worker (Celery, RQ, a cron job), or pass `webhookUrl` and save the file when Importly calls you back ([Webhooks](/docs/webhooks.md)), keeping a status check as a fallback. The [Celery guide](/docs/integrations/celery.md) and [Django guide](/docs/integrations/django.md) show both.
* Copy the file somewhere permanent, or set `store: true` to have every import land in your own bucket ([recipe](/docs/integrations/save-to-bucket.md)).
* For many links at once, see [Batch imports](/docs/integrations/batch-imports.md).

> [!NOTE]
>
> Downloads cost $0.002 per MB, with a $0.01 minimum, so a one-minute clip at 720p is usually two to four cents. The length check is \$0.003. 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.