> ## 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 Django without a task queue

> Transcribe or download any video or audio link from a Django app with no Celery or worker: start the job from a view, save the result from a signed webhook, and catch missed ones with a management command.

If your Django app takes video or podcast links, the download or transcript step 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 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.

You don't need Celery or a worker for this. A view starts the Importly job and stores its ID, Importly sends a signed webhook to your app when the job finishes, and a management command run from cron picks up any job whose webhook didn't arrive. If your project already runs Celery, see [Celery](/docs/integrations/celery.md) instead.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once). On the same page, under **Webhook signing secret**, click **Reveal** and copy the `whsec_…` secret. Add both to your server's environment, and to `.env` for development:

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

```bash theme={null}
pip install httpx
```

The code below saves to a `Video` model:

```python videos/models.py theme={null}
from django.db import models


class Video(models.Model):
    url = models.URLField(max_length=2000)
    importly_job_id = models.CharField(max_length=64, blank=True, db_index=True)
    importly_kind = models.CharField(max_length=16, blank=True)  # "transcribe" or "import"
    importly_status = models.CharField(max_length=16, blank=True)  # queued, running, completed, failed
    importly_result = models.JSONField(null=True, blank=True)
    importly_error = models.CharField(max_length=500, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
```

Run `python manage.py makemigrations && python manage.py migrate`.

## 2. A small client

A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) raises `ImportlyError` with the API's message. A webhook's result fields sit in `data` itself, while the status endpoint nests them under `result`, so `save_result` takes the job and its result separately:

```python videos/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
)

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


class ImportlyError(Exception):
    pass


def call(path, body=None, params=None):
    res = client.post(path, json=body) if body is not None else client.get(path, params=params)
    data = res.json()
    if res.is_success and data.get("success"):
        return data["data"]
    raise ImportlyError(f"Importly {res.status_code} {data.get('code', '')}: {data.get('error', 'request failed')}")


def save_result(video, job, result):
    video.importly_status = job["status"]
    if job["status"] == "completed":
        # a transcript has result["text"]; an import has result["mediaUrl"], valid for 7 days
        video.importly_result = result
    elif job["status"] == "failed":
        video.importly_error = f"{job.get('code')}: {job.get('message')}"[:500]
    video.save()
```

## 3. Start the job from a view

`"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 in this one call and is saved straight away. Anything still `queued` or `running` finishes later through the webhook. `maxCostDollars` caps what one link can cost:

```python videos/views.py theme={null}
from django.conf import settings
from django.shortcuts import redirect
from django.urls import reverse
from django.views.decorators.http import require_POST

from .importly import call, save_result
from .models import Video


@require_POST
def add_video(request):
    video = Video.objects.create(url=request.POST["url"], importly_kind="transcribe")
    job = call("/transcribe", {
        "url": video.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,
        "webhookUrl": settings.SITE_URL + reverse("importly-webhook"),
    })
    video.importly_job_id = job["jobId"]
    save_result(video, job, job.get("result"))
    return redirect("video-detail", pk=video.pk)
```

To download the file instead, call `POST /import` with `importly_kind="import"`. It returns a job ID straight away, and the webhook brings the `mediaUrl`:

```python theme={null}
job = call("/import", {
    "url": video.url,
    "includeVideo": True,  # False for audio only
    "videoQuality": "720p",  # a ceiling: lower if the source has no 720p
    "maxCostDollars": 0.5,  # the most this one file may cost
    "webhookUrl": settings.SITE_URL + reverse("importly-webhook"),
})
```

`webhookUrl` must be a public `https://` address, so set `SITE_URL` (for example `https://your-app.example`) in your settings. In local development, leave `webhookUrl` out and run the command in step 5 to fetch results.

## 4. The webhook view

Importly sends one `POST` when the job finishes. Check the `Importly-Signature` header against the raw `request.body` before you trust it: parsing the JSON first changes the bytes and the signature won't match. Django's CSRF check would reject the request, so the view is `csrf_exempt`; the signature does that job here:

```python videos/views.py theme={null}
import hashlib
import hmac
import json
import os
import time

from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt


def verify_importly_signature(header, raw_body, secret, tolerance_seconds=300):
    if not header:
        return False
    timestamp, signatures = None, []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t" and value.isdigit():
            timestamp = int(value)
        elif key == "v1":
            signatures.append(value)
    if timestamp is None or abs(time.time() - timestamp) > tolerance_seconds:
        return False
    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(signature, expected) for signature in signatures)


@csrf_exempt
@require_POST
def importly_webhook(request):
    if not verify_importly_signature(
        request.headers.get("Importly-Signature"), request.body, os.environ["IMPORTLY_WEBHOOK_SECRET"]
    ):
        return HttpResponseBadRequest()

    data = json.loads(request.body).get("data") or {}
    video = Video.objects.filter(importly_job_id=data.get("jobId")).first()
    # skip unknown jobs, and jobs the command in step 5 already finished
    if video and video.importly_status not in ("completed", "failed"):
        save_result(video, data, data)  # a webhook's result fields are in data itself
    return HttpResponse(status=200)
```

```python videos/urls.py theme={null}
from django.urls import path

from . import views

urlpatterns = [
    path("videos/add", views.add_video, name="add-video"),
    path("webhooks/importly", views.importly_webhook, name="importly-webhook"),
]
```

A finished transcript's `importly_result` has `text`, and `data.segments` with `start` and `end` times in seconds. A finished import's has `mediaUrl`, a link to the file that's valid for 7 days: copy it 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)). See [Webhooks](/docs/webhooks.md) for every payload.

## 5. Catch missed webhooks

Each job gets one webhook delivery and no retries, so a deploy or a brief outage can miss one. This command asks the status endpoint about every job that has been pending for more than two minutes:

```python videos/management/commands/check_importly_jobs.py theme={null}
from datetime import timedelta

from django.core.management.base import BaseCommand
from django.utils import timezone

from videos.importly import STATUS_PATH, ImportlyError, call, save_result
from videos.models import Video


class Command(BaseCommand):
    help = "Fetch results for Importly jobs whose webhook didn't arrive"

    def handle(self, *args, **options):
        pending = Video.objects.filter(
            importly_status__in=["queued", "running"],
            created_at__lt=timezone.now() - timedelta(minutes=2),
        ).exclude(importly_job_id="")[:100]
        for video in pending:
            try:
                job = call(STATUS_PATH[video.importly_kind], params={"id": video.importly_job_id})
            except ImportlyError as error:
                self.stderr.write(f"video {video.pk}: {error}")
                continue
            if job["status"] in ("completed", "failed"):
                save_result(video, job, job.get("result"))
            elif video.created_at < timezone.now() - timedelta(hours=1):
                video.importly_status = "failed"
                video.importly_error = f"still {job['status']} after an hour"
                video.save()
```

Run it every few minutes from cron, or from your platform's scheduler (Render, Railway, Heroku Scheduler, a Kubernetes CronJob):

```bash crontab theme={null}
*/5 * * * * cd /srv/app && python manage.py check_importly_jobs
```

## Notes

A caption transcript costs \$0.003; speech-to-text is billed per minute, and downloads by size. See [Transcripts](/docs/features/transcripts.md), [Downloads](/docs/features/downloads.md) and [Pricing](/docs/billing.md).

`SOURCE_THROTTLED` and `LIVE_NOT_SUPPORTED` are the failure codes that can work on a later attempt (a site that is busy for now, or a stream that is still live). For those, start the job 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 an account can have 50 imports queued or running at once. For hundreds of links, see [Batch imports](/docs/integrations/batch-imports.md).

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


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