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

# Import a batch of video links from your backend

> A backend recipe in TypeScript for importing hundreds of video or audio links: a cost cap per file, a steady send rate, webhooks plus a sweep for missed ones, and which errors to retry.

This recipe is for apps that take many links at once: a user uploads a CSV, pastes a list of episodes, or connects a feed, and your backend imports every one. The hard parts aren't the API call. They're not spending more than you meant to, not tripping rate limits, and not losing track of a job when a webhook never arrives.

The code is plain TypeScript with `fetch`. It assumes an `imports` table in your own database and a job that runs every minute (a cron route, a queue worker or a `setInterval` in a long-running server). Keep `IMPORTLY_API_KEY` on the server: create it on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once).

## 1. Store each link as a row

Write one row per link when the user submits the batch, and import from those rows rather than from the request. Then a restart, a deploy or a full balance never loses a link:

```ts lib/imports.ts theme={null}
export type ImportRow = {
  id: string
  batchId: string
  url: string
  state: 'waiting' | 'submitted' | 'done' | 'failed'
  jobId?: string
  attempts: number
  notBefore: Date // don't send before this time (used for retries)
  submittedAt?: Date
  mediaUrl?: string
  title?: string
  code?: string
  message?: string
}

// Your database, whatever it is: these are the only queries the recipe needs
export type ImportStore = {
  nextWaiting: (limit: number) => Promise<ImportRow[]>
  submittedBefore: (cutoff: Date) => Promise<ImportRow[]>
  byJobId: (jobId: string) => Promise<ImportRow | undefined>
  update: (id: string, changes: Partial<ImportRow>) => Promise<void>
}
```

Import one link per video. A `youtube.com/playlist?list=…` page is rejected with `PLAYLIST_NOT_SUPPORTED` before a job is created, so expand playlists into their video links before you store them. A watch URL with `&list=` in it is fine; it's treated as that one video.

## 2. Send at a steady pace

`POST /import` allows 240 requests per hour per key, so this sender starts at most 4 imports a minute, which fits under the limit with room for retries. Each import gets a `maxCostDollars` cap, because links in a batch come from users and one of them may be a three-hour 4K stream:

```ts lib/send-imports.ts theme={null}
import type { ImportStore } from './imports'

const API = 'https://api.importly.io'
const headers = {
  Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
  'Content-Type': 'application/json',
}

const later = (seconds: number) => new Date(Date.now() + seconds * 1000)

// Run once a minute
export const sendImports = async (store: ImportStore) => {
  const rows = await store.nextWaiting(4) // state 'waiting' and notBefore <= now, oldest first

  for (const row of rows) {
    let res: Response
    try {
      res = await fetch(`${API}/import`, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          url: row.url,
          includeVideo: true,
          videoQuality: '720p', // a ceiling: lower if the source has no 720p
          maxCostDollars: 0.5, // the most this one file may cost
          webhookUrl: `${process.env.APP_URL}/api/webhooks/importly`,
        }),
      })
    } catch {
      await store.update(row.id, { attempts: row.attempts + 1, notBefore: later(60) })
      continue
    }

    const body = await res.json()

    if (res.ok && body.success) {
      await store.update(row.id, { state: 'submitted', jobId: body.data.jobId, submittedAt: new Date() })
      continue
    }

    if (res.status === 429) {
      // over the hourly limit: leave the row waiting and stop this run
      await store.update(row.id, { notBefore: later(body.retryAfter ?? 60) })
      return
    }

    if (res.status === 402) {
      // balance too low: stop sending until credits are added; nothing was charged
      throw new Error(`Importly balance too low: ${body.error}`)
    }

    if (res.status >= 500) {
      const wait = Math.min(60 * 2 ** row.attempts, 3600)
      await store.update(row.id, { attempts: row.attempts + 1, notBefore: later(wait) })
      continue
    }

    // 400: a bad link (INVALID_URL, PLAYLIST_NOT_SUPPORTED). Resending won't change it
    await store.update(row.id, { state: 'failed', code: body.code, message: body.error })
  }
}
```

The `402` throws so your job runner stops and alerts you: every other link in the batch would get the same answer. Check the balance with [`GET /balance`](/docs/endpoints/balance) before a large batch if you'd rather warn the user up front. A 10-minute 720p video is about $0.15, so a batch of 200 of them is about $30.

## 3. Settle each job from the API

Importly sends one `POST` to `webhookUrl` when a job completes or fails. The handler takes only the `jobId` from it and reads the job 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). The same `settleJob` function is used again by the sweep in step 4:

```ts lib/settle-job.ts theme={null}
import type { ImportStore } from './imports'

// Failures worth another try later; everything else is final
const RETRY_LATER = new Set(['SOURCE_THROTTLED', 'LIVE_NOT_SUPPORTED'])
const MAX_ATTEMPTS = 3

export const settleJob = async (store: ImportStore, jobId: string) => {
  const row = await store.byJobId(jobId)
  if (!row || row.state !== 'submitted') return // unknown job, or already settled

  const res = await fetch(`https://api.importly.io/import/status?id=${encodeURIComponent(jobId)}`, {
    headers: { Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}` },
  })
  const body = await res.json()
  if (!body.success) return

  const job = body.data
  if (job.status === 'queued' || job.status === 'running') return // not finished yet

  if (job.status === 'completed') {
    const { mediaUrl, title } = job.result
    // mediaUrl expires after 7 days: copy the file now, or import with store: true
    await store.update(row.id, { state: 'done', mediaUrl, title })
    return
  }

  if (RETRY_LATER.has(job.code) && row.attempts + 1 < MAX_ATTEMPTS) {
    const wait = job.code === 'LIVE_NOT_SUPPORTED' ? 3600 : 120
    await store.update(row.id, {
      state: 'waiting',
      jobId: undefined,
      attempts: row.attempts + 1,
      notBefore: new Date(Date.now() + wait * 1000),
    })
    return
  }

  // MAX_COST_EXCEEDED, VIDEO_PRIVATE, VIDEO_UNAVAILABLE, AGE_RESTRICTED, …: show job.message to the user
  await store.update(row.id, { state: 'failed', code: job.code, message: job.message })
}
```

The webhook route only parses the body and hands the `jobId` over. It's a Next.js route handler here; in Express or Hono the body is the same:

```ts app/api/webhooks/importly/route.ts theme={null}
import { settleJob } from '@/lib/settle-job'
import { store } from '@/lib/db'

export async function POST(request: Request) {
  const { data } = await request.json()
  if (data?.type === 'import' && typeof data.jobId === 'string') {
    await settleJob(store, data.jobId)
  }
  return new Response(null, { status: 200 })
}
```

The webhook URL must be public `https://`. In local development there's no webhook, and the sweep below settles every job on its own.

## 4. Sweep for missed webhooks

Each job gets one webhook delivery and no retries, so a deploy or an outage on your side can miss one. Run the sweep from the same once-a-minute job as the sender:

```ts lib/sweep-imports.ts theme={null}
import type { ImportStore } from './imports'
import { settleJob } from './settle-job'

export const sweepImports = async (store: ImportStore) => {
  const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000)
  const stale = await store.submittedBefore(fiveMinutesAgo)

  for (const row of stale.slice(0, 50)) {
    if (row.jobId) await settleJob(store, row.jobId)
  }
}
```

A job that's still `queued` or `running` stays `submitted` and is checked again on the next run. Status checks allow 3,600 requests per hour, so 50 a minute leaves plenty of room. Long videos can take a few minutes to download; the sweep just keeps looking until they finish.

## What each failure means for a batch

| What you see | What the recipe does | Why |
| - | - | - |
| `429` on `POST /import` | Waits `retryAfter` seconds | Over the 240-per-hour limit for the key |
| `402`, `INSUFFICIENT_BALANCE` | Stops the whole batch | Every other link would fail the same way. Nothing is charged |
| `400`, `INVALID_URL` or `PLAYLIST_NOT_SUPPORTED` | Marks the link failed | Not a single video or audio page |
| Failed job, `SOURCE_THROTTLED` | Tries again in 2 minutes, up to 3 times | The source refused for a moment; a retry usually works |
| Failed job, `LIVE_NOT_SUPPORTED` | Tries again in an hour | The stream hadn't ended yet |
| Failed job, `MAX_COST_EXCEEDED` | Marks the link failed | The file costs more than `maxCostDollars`. Only the \$0.003 price check is charged |
| Failed job, `VIDEO_PRIVATE`, `VIDEO_UNAVAILABLE`, `AGE_RESTRICTED`, `AUTH_REQUIRED`, `GEO_BLOCKED` | Marks the link failed | The result won't change on a retry. Nothing is charged |

Failed imports aren't charged, except `MAX_COST_EXCEEDED` (the price check) and `FILE_TOO_LARGE`, where the file outgrew your balance partway and you pay for what was downloaded. All the codes are on [Errors & rate limits](/docs/error-handling.md).

> [!NOTE]
>
> Downloads cost $0.002 per MB, with a $0.01 minimum per import. Add `includeTranscript: true` to get the transcript in the same job, or `store: true` to have every file land in [your own bucket](/docs/integrations/save-to-bucket.md). 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 batch imports with Importly. It reads the same docs, fits the queue to your database and job runner, and can test with a few real links 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.