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

# Add transcripts to a Python app

> A working FastAPI recipe: a user sends a video link and gets the transcript back, with endpoints for the API call, polling, and a webhook for production. The same calls work in Flask or Django.

This recipe adds "send a link, get a transcript" to a Python backend with FastAPI. It covers videos without captions too, and the calls are plain HTTP, so they move to Flask, Django or a background worker unchanged. The key stays on your server.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and put it in your server's environment:

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

Install the two packages the code uses:

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

## 2. Start the transcript

`"mode": "auto"` uses the video's captions and falls back to speech-to-text when there are none. `wait` holds the request until the transcript is ready, so a captioned video usually comes back in this one call.

```python main.py theme={null}
import os

import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()
importly = httpx.AsyncClient(
    base_url="https://api.importly.io",
    headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
    timeout=70,  # longer than the 25s wait below
)


class TranscribeIn(BaseModel):
    url: str


def to_result(data: dict) -> dict:
    """Same shape for a finished, failed or still-running job."""
    result = data.get("result") or {}
    return {
        "jobId": data.get("jobId"),
        "status": data.get("status"),
        "text": result.get("text"),
        "segments": (result.get("data") or {}).get("segments"),
        "message": data.get("message"),
        "code": data.get("code"),
    }


def failed(res: httpx.Response, body: dict) -> JSONResponse:
    return JSONResponse(
        {"status": "failed", "message": body.get("error"), "code": body.get("code")},
        status_code=res.status_code,
    )


@app.post("/transcribe")
async def transcribe(payload: TranscribeIn):
    res = await importly.post(
        "/transcribe",
        # wait up to 25s for the result; cap speech-to-text on long videos at $0.50
        json={"url": payload.url, "mode": "auto", "wait": 25, "maxCostDollars": 0.5},
    )
    body = res.json()
    if res.is_error or not body.get("success"):
        return failed(res, body)
    return to_result(body["data"])
```

A rejected request (a bad link, a key problem, or a low balance) comes back with an HTTP error and an `error` message. A job that fails later, for example because the video is private, comes back with `status: "failed"`, a `code` and a `message`. See [Error handling](/docs/error-handling.md).

## 3. Poll if it's still running

Long videos without captions take longer than `wait`. Then the response has `status: "queued"` or `"running"` and a `jobId`. Your frontend calls this endpoint every few seconds until the status is `completed` or `failed`:

```python main.py theme={null}
@app.get("/transcribe/{job_id}")
async def transcribe_status(job_id: str):
    res = await importly.get("/transcribe/status", params={"id": job_id})
    body = res.json()
    if res.is_error or not body.get("success"):
        return failed(res, body)
    return to_result(body["data"])
```

`text` is the whole transcript. `segments` holds the same text with `start` and `end` times in seconds, which is what you want for chunking into a vector store, captions or search.

## 4. In production: save results with a webhook

When the transcript belongs to a record in your database, start the job with a `webhookUrl` instead of waiting, and store the `jobId` with the record:

```python theme={null}
json={"url": payload.url, "mode": "auto", "maxCostDollars": 0.5,
      "webhookUrl": "https://your-app.example/webhooks/importly"}
```

Importly sends one `POST` when the job finishes. This endpoint takes only the `jobId` from it and reads the result from the API with your key, so a forged request can't put data into your app. Every delivery is also signed: to reject forged requests before calling the API, check the `Importly-Signature` header as shown in [Verify signatures](/docs/webhooks.md#verify-signatures):

```python main.py theme={null}
@app.post("/webhooks/importly")
async def importly_webhook(request: Request):
    data = (await request.json()).get("data") or {}
    if data.get("type") != "transcribe" or not isinstance(data.get("jobId"), str):
        return {"ok": True}

    res = await importly.get("/transcribe/status", params={"id": data["jobId"]})
    body = res.json()
    if not body.get("success"):
        return {"ok": True}

    job = body["data"]
    if job["status"] == "completed":
        # find your record by job["jobId"] and save job["result"]["text"]
        ...
    elif job["status"] == "failed":
        # mark the record failed with job["code"] and job["message"]
        ...
    return {"ok": True}
```

Each job gets one delivery and no retries, so also check jobs that have been pending for a few minutes with the status endpoint. The webhook URL must be public `https://`, so a server on `localhost` gets nothing: poll in development. See [Webhooks](/docs/webhooks.md).

## Downloading the file instead

For the video or audio file itself, send the link to [`POST /import`](/docs/endpoints/import) and read [`GET /import/status`](/docs/endpoints/import-status) the same way. The finished job has `result.mediaUrl`, a link to the file that's valid for 7 days. Set `includeVideo: false` for audio only, or `store: true` to have it copied to [your own bucket](/docs/s3-storage.md). `/import` has no `wait`, so poll or use a webhook. See [Downloads](/docs/features/downloads.md).

> [!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).

## Let your agent write it

Using Claude Code or Cursor on this app? Connect the [MCP server](/docs/integrations/mcp.md) and ask it to add transcripts with Importly: it reads the same integration guide and can test with a real link first. See [Build with your agent](/docs/integrations/build-with-your-agent.md).


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