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

# Use Importly in Celery tasks

> Transcribe or download any video or audio link from a Celery task in a Django or Flask app, with retries that respect rate limits and never start the same job twice.

If your Django or Flask app hands video or podcast links to Celery, the media task is the one that breaks once it runs on a server: sites block datacenter IPs, and many videos have no captions to read. Call Importly from the task instead. It returns the transcript, a download link for the file, or the video's details, for links from YouTube, TikTok, Instagram, X, podcasts and 1,000+ other sites.

Long imports can take a few minutes, so don't hold a worker for them. One task starts the job, and a second task checks its status and schedules itself again with `self.retry(countdown=20)` until the job is done. A retry only ever re-runs the check, so it never starts the job twice.

This page uses Celery 5 with Redis as the broker and `httpx`.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once). Add it as `IMPORTLY_API_KEY` to the environment your Celery workers run in, and to `.env` for local development:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
```

```bash theme={null}
pip install "celery[redis]" httpx
```

## 2. A small client

The tasks share one helper. A `429` raises `RetryLater` with the `retryAfter` the API sent, and a `5xx` raises it with 30 seconds, so the task retries after that wait. A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) won't change on a retry, so it raises `Rejected` and the task fails:

```python myapp/importly.py theme={null}
import os

import httpx

client = httpx.Client(
    base_url="https://api.importly.io",
    headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
    timeout=70,  # longer than the 30-second wait on /transcribe
)


class RetryLater(Exception):
    """A 429 or 5xx: the same request can work after `seconds`."""

    def __init__(self, message: str, seconds: int):
        super().__init__(message)
        self.seconds = seconds


class Rejected(Exception):
    """A 400 (bad link), 401 (wrong key) or 402 (balance too low): a retry won't change it."""


def call(path: str, body: dict | None = None) -> dict:
    res = client.post(path, json=body) if body is not None else client.get(path)
    data = res.json()
    if res.is_success and data.get("success"):
        return data["data"]

    message = f"Importly {res.status_code} {data.get('code', '')}: {data.get('error', 'request failed')}"
    if res.status_code == 429:
        raise RetryLater(message, int(data.get("retryAfter", 60)))
    if res.status_code >= 500:
        raise RetryLater(message, 30)
    raise Rejected(message)
```

## 3. The tasks

`"mode": "auto"` uses the video's captions and falls back to speech-to-text when it has none. `wait: True` holds the request open for up to 30 seconds, so a transcript from captions usually comes back from the first call and is saved straight away. Anything still `queued` or `running` goes to `check_job`:

```python myapp/tasks.py theme={null}
from celery import Celery

from .importly import RetryLater, call

app = Celery("myapp", broker="redis://localhost:6379/0")

STATUS_PATH = {"transcribe": "/transcribe/status", "import": "/import/status"}


def save_result(record_id: int, kind: str, job: dict) -> None:
    """Write the finished or failed job to your database."""
    ...


def finish_or_check(record_id: int, kind: str, job: dict) -> None:
    if job["status"] in ("queued", "running"):
        check_job.apply_async((record_id, kind, job["jobId"]), countdown=20)
    else:
        save_result(record_id, kind, job)  # "completed" or "failed"


@app.task(bind=True, max_retries=5)
def transcribe_link(self, record_id: int, url: str) -> None:
    try:
        job = call("/transcribe", {
            "url": url,
            "mode": "auto",  # captions, or speech-to-text when there are none
            "wait": True,  # captions usually come back within the 30-second wait
            "maxCostDollars": 1,
        })
    except RetryLater as err:
        raise self.retry(exc=err, countdown=err.seconds)
    finish_or_check(record_id, "transcribe", job)


@app.task(bind=True, max_retries=5, rate_limit="4/m")
def import_link(self, record_id: int, url: str, audio_only: bool = False) -> None:
    try:
        job = call("/import", {
            "url": url,
            "includeVideo": not audio_only,
            "videoQuality": "720p",  # a ceiling: lower if the source has no 720p
            "maxCostDollars": 0.5,  # the most this one file may cost
        })
    except RetryLater as err:
        raise self.retry(exc=err, countdown=err.seconds)
    finish_or_check(record_id, "import", job)


# Checks every 20 seconds, for up to an hour
@app.task(bind=True, max_retries=180, ignore_result=True)
def check_job(self, record_id: int, kind: str, job_id: str) -> None:
    try:
        job = call(f"{STATUS_PATH[kind]}?id={job_id}")
    except RetryLater as err:
        raise self.retry(exc=err, countdown=err.seconds)
    if job["status"] in ("queued", "running"):
        raise self.retry(countdown=20)
    save_result(record_id, kind, job)
```

`save_result` is yours: store `job["result"]` on the record when `status` is `"completed"`, or `job["code"]` and `job["message"]` when it's `"failed"`. A transcript has `result["text"]`. An import has `result["mediaUrl"]`, a link to the file that's valid for 7 days, so copy the file to your storage if you keep it, or connect your bucket once and import with `store: True` ([Save to your bucket](/docs/integrations/save-to-bucket.md)).

A caption transcript costs \$0.003; speech-to-text is billed per minute, and `maxCostDollars` caps what one link can cost. More options are in [Transcripts](/docs/features/transcripts.md) and [Downloads](/docs/features/downloads.md).

## Run it

Queue the task from your view once the record is saved. In Django, `transaction.on_commit` makes sure the worker can read the row:

```python views.py theme={null}
from django.db import transaction

from myapp.tasks import transcribe_link

video = Video.objects.create(url=url)
transaction.on_commit(lambda: transcribe_link.delay(video.id, video.url))
```

Start a worker with `celery -A myapp.tasks worker --loglevel=info`. If your Django project already has a Celery app, use it in place of the `Celery(...)` line.

## Notes

`SOURCE_THROTTLED` and `LIVE_NOT_SUPPORTED` are the failure codes that can work on a later attempt (a stream that is still live, or a site that is busy for now). For those, queue `transcribe_link` or `import_link` again later; every other failure code is final. See [Media unavailable](/docs/errors/media-unavailable.md) and [Source throttled](/docs/errors/source-throttled.md).

`POST /import` allows 240 requests per hour per key, and `rate_limit="4/m"` keeps one worker under that. Celery applies `rate_limit` per worker, so divide it by the number of workers that run the task. An account can have 50 imports queued or running at once. Status endpoints allow 3,600 requests per hour per job type; a check every 20 seconds is 180 an hour for each job in progress, so about 20 jobs can poll at once. For hundreds of links, see [Batch imports](/docs/integrations/batch-imports.md).

Prefer a webhook? Start the job with a `webhookUrl` and save the result in a Django or Flask view, as in [Python (FastAPI)](/docs/integrations/python.md#4-in-production-save-results-with-a-webhook). Each job gets one delivery and no retries, so keep `check_job` as a fallback for jobs that stay pending. Running on AWS Lambda instead of a Celery worker? See the [AWS Lambda recipe](/docs/integrations/aws-lambda.md).

A `youtube.com/playlist?list=…` link is rejected with `PLAYLIST_NOT_SUPPORTED`. Queue one task per video instead.


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