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

# Show a preview for any video link in Python

> A FastAPI route that turns a pasted video link into a preview card: title, thumbnail, length and whether it's live, with polling, caching and the errors to handle.

When a user pastes a video link into your app, you usually want a preview before anything else: the title, a thumbnail and how long it is. Scraping that yourself means a different parser per site, and from a server many sites answer with a bot check instead of the page. This route sends the link to Importly's [basic metadata](/docs/features/metadata.md) endpoint and returns a small preview object. It runs on Python 3.9 or later with FastAPI and httpx. The same route in Node is [Video link previews in Node](/docs/recipes/video-link-preview-node.md).

## The code

```python preview.py theme={null}
import os
import time

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

api = httpx.Client(
    base_url="https://api.importly.io",
    headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
    timeout=30,
)

# The same link always gives the same preview, so look each one up once
cache: dict[str, dict] = {}


def get_preview(url: str) -> tuple[int, dict]:
    if url in cache:
        return 200, cache[url]

    # 1. Start the lookup. It returns a jobId right away.
    start = api.post("/metadata/basic", json={"url": url})
    started = start.json()
    if start.status_code >= 400 or not started.get("success"):
        # Rejected up front (not charged): not a valid link, a playlist, a bad key or a low balance
        return start.status_code, {"error": started.get("error"), "code": started.get("code")}

    # 2. Poll the status endpoint (free) until the job is done, for up to 30 seconds
    job = started["data"]
    for _ in range(20):
        if job["status"] not in ("queued", "running"):
            break
        time.sleep(1.5)
        job = api.get("/metadata/basic/status", params={"id": job["jobId"]}).json()["data"]

    if job["status"] == "failed":
        # e.g. VIDEO_UNAVAILABLE or VIDEO_PRIVATE. Failed lookups aren't charged.
        return 422, {"error": job.get("message"), "code": job.get("code")}
    if job["status"] != "completed":
        return 202, {"error": "Still looking this link up, try again in a moment"}

    result = job["result"]
    preview = {
        "url": url,
        "title": result["title"],
        "duration": result["duration"],
        "thumbnail": result["thumbnail"],
        "isLive": result["isLive"],
    }
    cache[url] = preview
    return 200, preview


app = FastAPI()


class PreviewRequest(BaseModel):
    url: str


@app.post("/api/preview")
def preview(body: PreviewRequest):
    # A plain def route: FastAPI runs it in a worker thread, so the polling doesn't block other requests
    url = body.url.strip()
    if not url:
        return JSONResponse({"error": "Send a url"}, status_code=400)
    status, data = get_preview(url)
    return JSONResponse(data, status_code=status)
```

```bash theme={null}
pip install fastapi uvicorn httpx
IMPORTLY_API_KEY=your_api_key uvicorn preview:app --port 3000

curl -X POST http://localhost:3000/api/preview \
  -H "Content-Type: application/json" \
  -d '{"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"}'
```

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and keep it on the server. The browser only calls your `/api/preview` route.

## What comes back

The finished job from `GET /metadata/basic/status` has four fields under `result`:

```json theme={null}
{
  "success": true,
  "data": {
    "jobId": "56380f26-3895-487a-8551-bc2a8b9c63ba",
    "status": "completed",
    "result": {
      "title": "Me at the zoo",
      "duration": 19,
      "thumbnail": "https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg",
      "isLive": false
    }
  }
}
```

`duration` is in seconds. A live stream that hasn't ended has `isLive: true` and `duration: null`, so show a "Live" badge instead of a length. It can't be downloaded or transcribed until the stream ends.

For the description, uploader, upload date or view counts, call [`POST /metadata`](/docs/endpoints/metadata) instead. It costs the same and returns everything the source exposes.

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `400` with an `error` message | Not a valid link, or a playlist page (`PLAYLIST_NOT_SUPPORTED`). Ask for a single video link |
| Start request | HTTP `401` | The key is missing or wrong. Check `IMPORTLY_API_KEY` |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Add credits; nothing was charged |
| Start request | HTTP `429` | Wait `retryAfter` seconds and retry |
| Status | `status: "failed"`, `code: "VIDEO_UNAVAILABLE"` or `"VIDEO_PRIVATE"` | The video is gone or private; show that on the card |

Every error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.md).

## In production

* Swap the `cache` dict for your database or Redis, keyed by the link, so a preview is looked up once across restarts and workers. With several uvicorn or gunicorn workers, each one has its own dict.
* If you store the thumbnail, copy the image to your own storage. Some platforms sign their image links, and those stop working after a while.
* Use `duration` to check a video before a bigger job: reject anything over your length limit before you pay to [download](/docs/features/downloads.md) or [transcribe](/docs/features/transcripts.md) it.
* Saving previews in the background (a feed, a Celery task)? Pass a `webhookUrl` and save the result when Importly calls you back. See [Webhooks](/docs/webhooks.md) and [Celery](/docs/integrations/celery.md).

> [!NOTE]
>
> A preview costs \$0.003 per link, and status checks are free. 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.