2026-11-21 · 5 min read

How to Caption Videos with AWS Lambda

AI-generated hero image: a dark 35mm film strip with the word LAMBDA glowing in orange neon at the center.
This image was generated with AI.

Lambda is a natural fit for caption jobs that start from an event: an upload to S3, a row in DynamoDB, or an HTTP call from your app. The caption.sh API is a plain HTTPS API, so a function can drive it with nothing but the Python standard library.

Submit from a handler

POST your video URL to the API. Styling options ride along in the nested options object.

import json, os, urllib.request

API = "https://api.caption.sh"
KEY = os.environ["CAPTION_API_KEY"]

def api(path, payload=None):
    req = urllib.request.Request(
        API + path,
        data=json.dumps(payload).encode() if payload else None,
        method="POST" if payload else "GET",
    )
    req.add_header("Authorization", "Bearer " + KEY)
    if payload:
        req.add_header("Content-Type", "application/json")
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read())

def lambda_handler(event, context):
    job = api("/v1/videos", {
        "source_url": event["video_url"],
        "options": {"caps": True, "highlight": True},
    })
    return {"job_id": job["job_id"]}

Each job accepts a video up to 10 minutes long. For longer sources, split them into segments first and fan out one job per segment.

Poll without holding a function open forever

Jobs move through queued, awaiting_upload, running, and then done or error. A simple pattern is to poll inside the invocation with a deadline that sits comfortably under your function timeout, and treat a missed deadline as its own exit.

import time

def wait_for_job(job_id, deadline_seconds=600):
    deadline = time.time() + deadline_seconds
    while time.time() < deadline:
        st = api("/v1/jobs/" + job_id)
        if st["status"] == "done":
            return True
        if st["status"] == "error":
            raise RuntimeError("caption job failed")
        time.sleep(15)
    raise TimeoutError("job " + job_id + " not done in time")

For long batches, prefer two small functions or a Step Functions workflow: one submits, the other checks later. That keeps individual invocations short and cheap. A 429 response means you hit the transcription throughput ceiling; back off and retry rather than hammering the endpoint.

Fetch the finished video

The result endpoint answers with a 302 redirect to the file. With urllib, install a handler that does not follow redirects so you can read the Location header.

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None

def result_url(job_id):
    opener = urllib.request.build_opener(NoRedirect())
    req = urllib.request.Request(API + "/v1/jobs/" + job_id + "/result")
    req.add_header("Authorization", "Bearer " + KEY)
    try:
        opener.open(req)
    except urllib.error.HTTPError as e:
        if e.code == 302:
            return e.headers["Location"]
        raise

Results are stored for 24 hours, then deleted, so copy the file to S3 in the same invocation or soon after. Cost is prepaid at $0.10 per minute of video; pair that with Lambda's per-invocation pricing and a captioned clip usually costs well under a dime end to end.

Good fits for this setup

  • Event-driven pipelines where a new upload should come back captioned.
  • Batch back-catalog jobs where Step Functions can fan out segments.
  • Teams that want captions without running an always-on worker.

Burned-in captions are fixed in the frame: viewers cannot toggle, resize, or translate them. When accessibility matters, keep the platform's native caption track available too.

Back to all articles