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

# Save transcripts to DynamoDB from AWS Lambda

> A tested AWS Lambda recipe in Python: start a transcript behind API Gateway, receive Importly's signed webhook on a Function URL, save the result to DynamoDB once, and sweep up any job whose webhook was missed.

A transcript or download feature that works on your laptop often fails once it runs on Lambda: YouTube and other sites block AWS IP addresses, many videos have no captions to read, and a downloader binary plus ffmpeg doesn't fit a function well. Send the link to Importly from Lambda instead and save what comes back in DynamoDB.

This recipe is three handlers in one file and one table:

* `app.start`, behind an API Gateway HTTP API with a JWT authorizer, starts the job for a signed-in user and writes an item.
* `app.webhook`, on a Lambda Function URL, receives Importly's signed webhook and fills in the item.
* `app.sweep`, on an EventBridge schedule, finishes any item whose webhook never arrived.

The code uses only the standard library and `boto3`, which the Lambda Python runtime already includes, so there's nothing to package. Tested on Python 3.11 against a mocked DynamoDB (moto) and a mocked API.

## 1. The table and settings

Create a DynamoDB table named `transcripts` with the partition key `job_id` (string). Give the function's role `dynamodb:PutItem`, `UpdateItem` and `Scan` on it.

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once), and copy the **Webhook signing secret** (it starts with `whsec_`) from the same page. Set these environment variables on the function, or load them from Secrets Manager:

| Variable | Value |
| - | - |
| `IMPORTLY_API_KEY` | Your API key |
| `IMPORTLY_WEBHOOK_SECRET` | The `whsec_…` signing secret |
| `IMPORTLY_WEBHOOK_URL` | The Function URL of the webhook handler (step 3) |
| `TRANSCRIPTS_TABLE` | `transcripts` |

## 2. The handlers

`save_job` is shared: the webhook and the sweep both read the job from the status endpoint with your key, and a conditional update only writes an item that is still `queued` or `running`. A second delivery, or the sweep finding a job the webhook already saved, does nothing.

```python app.py theme={null}
import base64
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

import boto3
from boto3.dynamodb.conditions import Attr
from botocore.exceptions import ClientError

table = boto3.resource("dynamodb").Table(os.environ["TRANSCRIPTS_TABLE"])
API = "https://api.importly.io"
PENDING = ("queued", "running")


def importly(path, body=None):
    """Call the API and return (HTTP status, parsed body), errors included."""
    req = urllib.request.Request(
        API + path,
        data=json.dumps(body).encode() if body is not None else None,
        method="POST" if body is not None else "GET",
        headers={
            "Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}",
            "Content-Type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=20) as res:
            return res.status, json.load(res)
    except urllib.error.HTTPError as err:
        return err.code, json.load(err)


def save_job(job_id):
    """Read the job from the API and save it to its item, once."""
    status, body = importly(f"/transcribe/status?id={urllib.parse.quote(job_id)}")
    if not body.get("success"):
        return
    job = body["data"]
    if job["status"] not in ("completed", "failed"):
        return
    result = job.get("result") or {}
    try:
        table.update_item(
            Key={"job_id": job_id},
            UpdateExpression="SET #status = :s, #text = :t, #segments = :seg, error_code = :c, error_message = :m, updated_at = :now",
            # a second delivery, or the sweep after the webhook, does nothing
            ConditionExpression=Attr("status").is_in(list(PENDING)),
            # status, text and segments are DynamoDB reserved words, so they go through names
            ExpressionAttributeNames={"#status": "status", "#text": "text", "#segments": "segments"},
            ExpressionAttributeValues={
                ":s": job["status"],
                ":t": result.get("text"),
                ":seg": json.dumps((result.get("data") or {}).get("segments")),
                ":c": job.get("code"),
                ":m": job.get("message"),
                ":now": datetime.now(timezone.utc).isoformat(),
            },
        )
    except ClientError as err:
        if err.response["Error"]["Code"] != "ConditionalCheckFailedException":
            raise


def reply(status_code, body=None):
    return {"statusCode": status_code, "headers": {"Content-Type": "application/json"}, "body": json.dumps(body or {})}


# API Gateway HTTP API with a JWT authorizer (Cognito, Clerk, Auth0, Supabase…)
def start(event, context):
    user_id = event["requestContext"]["authorizer"]["jwt"]["claims"]["sub"]
    url = json.loads(event.get("body") or "{}").get("url")
    if not isinstance(url, str):
        return reply(400, {"error": "Send a url"})

    status, body = importly("/transcribe", {
        "url": url,
        "mode": "auto",  # captions, or speech-to-text when there are none
        "maxCostDollars": 0.5,  # stop a long video without captions before it costs more
        "webhookUrl": os.environ["IMPORTLY_WEBHOOK_URL"],
    })
    if not body.get("success"):
        return reply(status, {"error": body.get("error"), "code": body.get("code")})

    job = body["data"]
    table.put_item(Item={
        "job_id": job["jobId"],
        "user_id": user_id,
        "url": url,
        "status": job["status"],
        "created_at": int(time.time()),
    })
    return reply(200, {"id": job["jobId"], "status": job["status"]})


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)


# Lambda Function URL, auth type NONE: the signature check keeps other callers out
def webhook(event, context):
    # the raw bytes: the signature covers exactly what Importly sent
    raw = event.get("body") or ""
    raw_body = base64.b64decode(raw) if event.get("isBase64Encoded") else raw.encode()
    header = (event.get("headers") or {}).get("importly-signature")
    if not verify_importly_signature(header, raw_body, os.environ["IMPORTLY_WEBHOOK_SECRET"]):
        return {"statusCode": 400}

    data = json.loads(raw_body).get("data") or {}
    if data.get("type") == "transcribe" and isinstance(data.get("jobId"), str):
        save_job(data["jobId"])
    return {"statusCode": 200}


# EventBridge schedule, every 5 minutes: each job gets one webhook delivery and no retries
def sweep(event, context):
    five_minutes_ago = int(time.time()) - 5 * 60
    pending = table.scan(
        FilterExpression=Attr("status").is_in(list(PENDING)) & Attr("created_at").lt(five_minutes_ago),
        ProjectionExpression="job_id",
    )
    for item in pending["Items"]:
        save_job(item["job_id"])
    return {"checked": len(pending["Items"])}
```

`start` sends `"mode": "auto"`, which uses the video's captions and falls back to speech-to-text when there are none. A rejected request (a bad link, a key problem, or a low balance) comes back with its HTTP status, an `error` and a `code`, and no item is written. See [Error handling](/docs/error-handling.md).

`webhook` checks the signature against the raw body. Function URLs and API Gateway can deliver it base64-encoded, so it decodes first when `isBase64Encoded` is set. It takes only the `jobId` from the payload and reads the result from the API with your key. Right after you rotate the signing secret, Importly sends two `v1` signatures for 24 hours, and this check accepts either. See [Webhooks](/docs/webhooks.md#verify-signatures).

`segments` is saved as a JSON string with `start` and `end` times in seconds, for captions, chapters or search. A job that fails later, for example because the video is private, is saved with `status: "failed"` and its `error_code` and `error_message`.

## 3. Wire it up

Create one function with the Python 3.11 runtime (or newer), upload `app.py`, and point three entry points at it:

* An API Gateway HTTP API route `POST /transcripts` with a JWT authorizer from your auth provider, integrated with a function whose handler is `app.start`.
* A function with handler `app.webhook` and a Function URL with auth type `NONE`. Set its URL as `IMPORTLY_WEBHOOK_URL`. The signature check is what keeps other callers out.
* An EventBridge Scheduler schedule `rate(5 minutes)` that invokes a function with handler `app.sweep`.

Each job gets one webhook delivery and no retries, which is what the sweep is for. It scans the table, which is fine for a few thousand items; for more, add a global secondary index on `status` and query it instead.

Your app calls the route with the user's token and reads the item back (through your own API) until `status` is `completed` or `failed`.

## Downloading the file instead

For the video or audio file itself, start [`POST /import`](/docs/endpoints/import) the same way and save `mediaUrl` from [`GET /import/status`](/docs/endpoints/import-status) in `save_job`. That link is valid for 7 days, so store the file if your app needs it longer: with `store: true`, each import is copied to your own S3 bucket ([recipe](/docs/integrations/save-to-bucket.md)). Set `includeVideo: false` for audio only. See [Downloads](/docs/features/downloads.md).

For a long-running Python server instead of Lambda, see [Python (FastAPI)](/docs/integrations/python.md), or [Celery](/docs/integrations/celery.md) for task queues.

> [!NOTE]
>
> A transcript from captions costs $0.003. Speech-to-text for a video without captions is $0.01 per minute, and `maxCostDollars` stops a long one before it's charged. 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.