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

# Download a TikTok video in Python

> Python code that takes a TikTok link, gets the MP4 through the Importly API and saves it, plus a batch version for a list of links, with a cost cap and the errors to handle.

Your Python backend has TikTok links, pasted by users or collected by a scraper, and needs the video files. Fetching TikTok yourself works on a laptop and gets blocked once the code runs on a server, so this sends each link to Importly and saves the finished MP4. It needs only `requests`. The [Node version](/docs/recipes/tiktok-video-node.md) does the same in JavaScript.

## One video

```python download_tiktok.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 download_tiktok(tiktok_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": tiktok_url, "videoQuality": "720p", "maxCostDollars": 0.1},
        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"))

    # 2. Poll until the job is done (a short TikTok usually takes a few seconds).
    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 VIDEO_UNAVAILABLE. Failed imports aren't charged.
        raise ImportlyError(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_tiktok(sys.argv[1], "tiktok.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_tiktok.py "https://www.tiktok.com/@<user>/video/<id>"
```

`maxCostDollars` caps what one file may cost. A short TikTok is about a cent, so `0.1` only stops an unusually long video; that job fails with `MAX_COST_EXCEEDED` instead of downloading. See [Capping the cost](/docs/endpoints/import.md#capping-the-cost).

Share links such as `vm.tiktok.com/...` work as they are, so you can pass on whatever your users paste. If the post behind a share link has been deleted or made private, the job fails with `VIDEO_UNAVAILABLE` ("the TikTok short link no longer leads to a post"), so show that message to the user rather than retrying. See [Media unavailable](/docs/errors/media-unavailable.md).

## A list of videos

If another library or a scraper already gives you video URLs (a user's posts, a hashtag, a search), you only need the files. This downloads them a few at a time and keeps going when one fails. Add it to `download_tiktok.py` above:

```python download_tiktok.py theme={null}
from concurrent.futures import ThreadPoolExecutor


def download_many(urls: list[str], folder: str = "tiktoks", workers: int = 3) -> None:
    os.makedirs(folder, exist_ok=True)

    def one(index_and_url):
        index, url = index_and_url
        try:
            result = download_tiktok(url, os.path.join(folder, f"{index:04d}.mp4"))
            return url, "ok", result["totalCostInDollars"]
        except ImportlyError as error:
            return url, error.code, 0

    with ThreadPoolExecutor(max_workers=workers) as pool:
        for url, outcome, cost in pool.map(one, enumerate(urls)):
            print(f"{outcome:<20} ${cost:<6} {url}")
```

```python theme={null}
download_many(open("links.txt").read().split())
```

Keep `workers` small. `POST /import` allows 240 requests per hour per key and 50 imports queued or running at once, and going over either returns `429` with `retryAfter`. For hundreds of links, use webhooks and a steady send rate instead: [Batch imports](/docs/integrations/batch-imports.md) has a sender that handles both.

## 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 TikTok caption",
      "duration": 14,
      "fileSizeBytes": 1837204,
      "costInDollars": 0.01,
      "totalCostInDollars": 0.01
    }
  }
}
```

TikTok videos are portrait, so `720p` means 720 pixels on the short side (720×1280). 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 video |
| 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 `"VIDEO_UNAVAILABLE"` | The video is private or gone; tell the user |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | The video costs more than your cap; raise it or skip the link |

Every error has a `documentationUrl` with the fix. See [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) guide](/docs/integrations/python.md) shows the endpoints, and [Celery](/docs/integrations/celery.md) covers background workers.
* 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)).
* Only download videos your users have the right to use.

> [!NOTE]
>
> Downloads cost $0.002 per MB, with a $0.01 minimum, so a short TikTok is usually about a cent. 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.