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

# Playlists, channels and feeds

> List the items of a YouTube playlist or channel, a TikTok profile, an album or a podcast feed, page through them with a cursor, and import or transcribe each one from your backend.

Some apps take a link that stands for many videos or episodes: a course importer that takes a YouTube playlist, a clip tool that follows a creator's channel, a podcast archive that takes a feed. Your backend needs every item in it as a link of its own.

[`POST /collection`](/docs/endpoints/collection) lists the items of a playlist, channel, profile, album or podcast feed, a page at a time, without downloading anything. Each item comes with a `url` you send to [`/import`](/docs/features/downloads), [`/transcribe`](/docs/features/transcripts) or [`/metadata`](/docs/features/metadata), one item per request. A page costs \$0.003, up to 200 items.

## Which links work

| Link | Example | Lists |
| - | - | - |
| YouTube playlist | `youtube.com/playlist?list=PL…` | The playlist's videos. A watch link with `&list=PL…` lists that playlist too |
| YouTube channel | `youtube.com/@name`, `youtube.com/channel/UC…` | The channel's videos. Send its `/shorts` or `/streams` link for its Shorts or live streams |
| TikTok profile | `tiktok.com/@name` | The profile's videos |
| SoundCloud set or profile | `soundcloud.com/artist/sets/name`, `soundcloud.com/artist/tracks` | The tracks |
| Bandcamp album or artist page | `artist.bandcamp.com/album/name`, `artist.bandcamp.com` | An album's tracks; an artist page's albums, each marked `isCollection: true` |
| Vimeo showcase, channel or user | `vimeo.com/showcase/123`, `vimeo.com/channels/name` | The videos |
| Podcast RSS feed | `feeds.example.com/show.xml` | The episodes, each `url` being the episode's audio file |

List pages on other sites often work too: send the link and see. These don't:

| Link | What you get |
| - | - |
| A single video or episode | `NOT_A_COLLECTION`, not charged. Send it to `/import`, `/transcribe` or `/metadata` |
| A YouTube Mix (`list=RD…`) | `COLLECTION_NOT_SUPPORTED`, not charged. Mixes are made for each viewer and change on every visit |
| X and Instagram profiles | `COLLECTION_NOT_SUPPORTED`, not charged: these sites only show a profile's posts to signed-in visitors. Send each post's link instead |
| Private or deleted playlists | A failed job, not charged, with the same codes as other media that can't be fetched |
| A very large podcast feed | Can fail with `COLLECTION_TOO_LARGE`, not charged. See [Limits](#limits) |

## List a playlist

```bash cURL theme={null}
curl -X POST https://api.importly.io/collection \
  -H "Authorization: Bearer $IMPORTLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://www.youtube.com/playlist?list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH", "limit": 200}'

# then, with the jobId from the response
curl "https://api.importly.io/collection/status?id=$JOB_ID" \
  -H "Authorization: Bearer $IMPORTLY_API_KEY"
```

```javascript Node.js theme={null}
const res = await fetch('https://api.importly.io/collection', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ url: 'https://www.youtube.com/playlist?list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH', limit: 200 }),
})
const body = await res.json()
if (!body.success) throw new Error(`${body.code}: ${body.error} (${body.documentationUrl})`)
console.log(body.data.jobId) // poll GET /collection/status?id=…
```

```python Python theme={null}
import os
import requests

res = requests.post(
    "https://api.importly.io/collection",
    headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
    json={"url": "https://www.youtube.com/playlist?list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH", "limit": 200},
)
body = res.json()
if not body["success"]:
    raise SystemExit(f"{body['code']}: {body['error']} ({body['documentationUrl']})")
print(body["data"]["jobId"])  # poll GET /collection/status?id=…
```

Like every endpoint, listing runs as a job. Poll `GET /collection/status?id={jobId}` every few seconds, or pass a `webhookUrl` and get the page [by webhook](/docs/endpoints/webhooks/collection.md). A completed page looks like this:

```json theme={null}
{
  "success": true,
  "data": {
    "jobId": "7d2f9c1e-4b8a-4e3f-9a6d-2c5b1e0f8a73",
    "status": "completed",
    "result": {
      "collection": {
        "id": "PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH",
        "url": "https://www.youtube.com/playlist?list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH",
        "title": "Coding Challenges",
        "uploader": "The Coding Train",
        "itemCount": 246
      },
      "items": [
        {
          "id": "17WoOqgXsRM",
          "url": "https://www.youtube.com/watch?v=17WoOqgXsRM",
          "title": "Coding Challenge 1: Starfield Simulation",
          "duration": 834,
          "isLive": false,
          "isCollection": false
        },
        {
          "id": "LG8ZK-rRkXo",
          "url": "https://www.youtube.com/watch?v=LG8ZK-rRkXo",
          "title": "Coding Challenge #2: Menger Sponge Fractal",
          "duration": 841,
          "isLive": false,
          "isCollection": false
        }
      ],
      "nextCursor": "eyJ2IjoxLCJoIjoi…",
      "truncated": false,
      "costInDollars": 0.003
    }
  }
}
```

## Item fields

| Field | Meaning |
| - | - |
| `id` | The item's id on its site. Podcast feeds give episodes no id, so for those it's a stable id made from the episode's link. Use it to skip items you already have |
| `url` | The item's own link, ready for `/import`, `/transcribe` or `/metadata`. For a podcast episode, it's the audio file's link from the feed |
| `title` | `null` where the site's list doesn't include it (SoundCloud sets, Vimeo showcases) |
| `duration` | Length in seconds. `null` for YouTube Shorts, SoundCloud, Bandcamp and Vimeo items and for live streams. When you need it, [`POST /metadata/basic`](/docs/endpoints/basic-metadata) has it for \$0.003 |
| `isLive` | `true` for a YouTube live stream that hasn't ended. Importing or transcribing it fails with `LIVE_NOT_SUPPORTED` until it ends, so skip it and try again later. `false` for other YouTube items, `null` on other sites |
| `isCollection` | `true` when the item is a list itself, such as an album on a Bandcamp artist page. Send its `url` to `/collection`, not `/import` |

The `collection` object has the list's `id`, `url`, `title` and `uploader`, and `itemCount` when the site says how many items there are (or once the whole list is known); `null` otherwise.

## Page through a collection

Send the same `url` with the previous page's `nextCursor` as `cursor` to get the next page. `nextCursor` is `null` on the last page. Every page costs the same, so use `limit: 200` when you want the whole list: 1,000 items is 5 pages, \$0.015.

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

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

// One page: start the listing job, then poll it until it finishes
const listPage = async (url, cursor) => {
  const res = await fetch(`${API}/collection`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ url, cursor, limit: 200 }),
  })
  const body = await res.json()
  if (!body.success) throw new Error(`${body.code}: ${body.error}`)

  for (;;) {
    await sleep(2000)
    const status = await (await fetch(`${API}/collection/status?id=${body.data.jobId}`, { headers })).json()
    if (!status.success) throw new Error(`${status.code}: ${status.error}`)
    const job = status.data
    if (job.status === 'completed') return job.result
    if (job.status === 'failed') throw new Error(`${job.code}: ${job.message}`)
  }
}

// Every item in the collection, page by page ($0.003 a page)
export async function* collectionItems(url) {
  let cursor
  do {
    const page = await listPage(url, cursor)
    yield* page.items
    cursor = page.nextCursor
  } while (cursor)
}
```

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

API = "https://api.importly.io"
HEADERS = {"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"}


def list_page(url, cursor=None):
    """One page: start the listing job, then poll it until it finishes."""
    payload = {"url": url, "limit": 200}
    if cursor:
        payload["cursor"] = cursor
    body = requests.post(f"{API}/collection", headers=HEADERS, json=payload, timeout=30).json()
    if not body["success"]:
        raise RuntimeError(f"{body['code']}: {body['error']}")

    while True:
        time.sleep(2)
        status = requests.get(
            f"{API}/collection/status", headers=HEADERS, params={"id": body["data"]["jobId"]}, timeout=30
        ).json()
        if not status["success"]:
            raise RuntimeError(f"{status['code']}: {status['error']}")
        job = status["data"]
        if job["status"] == "completed":
            return job["result"]
        if job["status"] == "failed":
            raise RuntimeError(f"{job['code']}: {job['message']}")


def collection_items(url):
    """Every item in the collection, page by page ($0.003 a page)."""
    cursor = None
    while True:
        page = list_page(url, cursor)
        yield from page["items"]
        cursor = page["nextCursor"]
        if not cursor:
            return
```

A cursor only works with the `url` it came from; any other `url`, or an edited cursor, gets a `400` with `INVALID_CURSOR`. To have each page pushed to you instead of polling, pass `webhookUrl` and start the next page from the webhook handler with the `nextCursor` in it.

## Import every item

Each item is an ordinary link, so imports from a collection follow the usual [limits](/docs/error-handling.md#jobs-in-progress): 240 imports an hour per key, 2 running at once, and at most 50 queued or running. A playlist of 300 videos is over that last cap on purpose. Don't send them all at once: save the items, submit a few, let the webhook tell you when each one finishes, then submit more.

First save every item as a row in your database. Skip live streams, and keep `isCollection` items aside to list on their own:

```javascript lib/add-collection.js theme={null}
import { collectionItems } from './collection'

// store.add inserts a row, ignoring an id it already has, so a link listed twice is imported once
export const addCollection = async (store, url) => {
  const nested = []
  for await (const item of collectionItems(url)) {
    if (item.isCollection) nested.push(item.url) // a list itself: call addCollection on it later
    else if (item.isLive) continue // a stream that hasn't ended: imports fail until it does
    else await store.add({ id: item.id, url: item.url, title: item.title, state: 'waiting' })
  }
  return nested
}
```

```python add_collection.py theme={null}
from collection import collection_items


def add_collection(store, url):
    """store.add inserts a row, ignoring an id it already has, so a link listed twice is imported once."""
    nested = []
    for item in collection_items(url):
        if item["isCollection"]:
            nested.append(item["url"])  # a list itself: call add_collection on it later
        elif item["isLive"]:
            continue  # a stream that hasn't ended: imports fail until it does
        else:
            store.add(id=item["id"], url=item["url"], title=item["title"], state="waiting")
    return nested
```

Then run a sender once a minute. It keeps at most 20 imports in flight, well under the cap of 50, so other imports your app starts still have room, and sends at most 4 a minute, under 240 an hour:

```javascript lib/send-imports.js theme={null}
const MAX_IN_FLIGHT = 20
const PER_RUN = 4

// Run once a minute
export const sendImports = async (store) => {
  const room = MAX_IN_FLIGHT - (await store.countSubmitted())
  if (room <= 0) return // the webhook frees room as imports finish
  const rows = await store.nextWaiting(Math.min(room, PER_RUN))

  for (const row of rows) {
    const res = await fetch('https://api.importly.io/import', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        url: row.url,
        videoQuality: '720p',
        maxCostDollars: 0.5, // the most one file may cost
        webhookUrl: `${process.env.APP_URL}/api/webhooks/importly`,
      }),
    })
    const body = await res.json()

    if (res.ok && body.success) {
      await store.update(row.id, { state: 'submitted', jobId: body.data.jobId })
    } else if (res.status === 429 || res.status >= 500) {
      return // over a limit, or a hiccup: the row stays waiting for the next run
    } else if (res.status === 402) {
      throw new Error(`Importly balance too low: ${body.error}`) // stop and alert: every row would get this
    } else {
      await store.update(row.id, { state: 'failed', code: body.code, message: body.error })
    }
  }
}
```

```python send_imports.py theme={null}
import os
import requests

MAX_IN_FLIGHT = 20
PER_RUN = 4


def send_imports(store):
    """Run once a minute."""
    room = MAX_IN_FLIGHT - store.count_submitted()
    if room <= 0:
        return  # the webhook frees room as imports finish
    for row in store.next_waiting(min(room, PER_RUN)):
        res = requests.post(
            "https://api.importly.io/import",
            headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
            json={
                "url": row["url"],
                "videoQuality": "720p",
                "maxCostDollars": 0.5,  # the most one file may cost
                "webhookUrl": f"{os.environ['APP_URL']}/api/webhooks/importly",
            },
            timeout=30,
        )
        body = res.json()

        if res.ok and body["success"]:
            store.update(row["id"], state="submitted", job_id=body["data"]["jobId"])
        elif res.status_code == 429 or res.status_code >= 500:
            return  # over a limit, or a hiccup: the row stays waiting for the next run
        elif res.status_code == 402:
            raise RuntimeError(f"Importly balance too low: {body['error']}")  # stop and alert
        else:
            store.update(row["id"], state="failed", code=body["code"], message=body["error"])
```

The webhook handler moves each finished import's row out of `submitted`, which makes room for the next run. Write it, and a sweep for missed webhooks, as in [Batch imports](/docs/integrations/batch-imports.md#3-settle-each-job-from-the-api): the handler reads the job with your key, saves `mediaUrl` on success, and requeues a failure that has `retryable: true`. A transcript per item works the same way with [`POST /transcribe`](/docs/features/transcripts), which allows 3 running and 50 queued or running.

`maxCostDollars` stops one long video from spending more than you meant. When `duration` is in the list you can also skip items over a length you care about before importing; when it's `null`, the cap still protects you.

## Limits

> [accordion] Lists are a snapshot for about an hour
>
> Pages of the same link come from the same list as long as you keep paging: each page keeps the list for another hour. A cursor only works with the list it came from, so once a list has gone unused for an hour its cursors expire: the job fails with `INVALID_CURSOR` and isn't charged. List again from the first page, which also picks up what's new. Dedupe on `id` across separate listings.

> [accordion] Up to 5,000 items per link
>
> Importly lists the first 5,000 items of a collection, in the collection's own order. When there are more, the last page has `nextCursor: null` and `truncated: true`. If the site says up front how many items it has, `truncated` is `true` from the first page; otherwise it becomes `true` when you reach the end of what's listed. Very long lists can stop before 5,000, also with `truncated: true`. For a channel's newest uploads, the first pages are the ones you want.

> [accordion] Private and deleted YouTube videos
>
> YouTube lists don't include private or deleted videos, as on YouTube's own playlist page. YouTube can also leave out a few videos it limits to some regions. `itemCount` is the number of videos you can get, so it can be lower than the count YouTube shows.

> [accordion] YouTube channels list their videos
>
> A channel link lists the channel's videos, newest first. Its Shorts and live streams are separate lists: send `youtube.com/@name/shorts` or `youtube.com/@name/streams`. A channel with no regular videos lists its Shorts and live tabs instead, as items with `isCollection: true` that you list in turn.

> [accordion] Very large podcast feeds
>
> A feed with a very long archive, such as a daily show's, can be too big to list right now and fails with `COLLECTION_TOO_LARGE`, at no charge. Retrying the same feed won't help.

> [accordion] Empty collections
>
> A playlist with no items completes with `items: []` and is charged like any other page.

## Errors

| `code` | Where you see it | What to do |
| - | - | - |
| `NOT_A_COLLECTION` | `400` response, or a failed job | The link is one video or episode. Send it to `/import`, `/transcribe` or `/metadata` |
| `COLLECTION_NOT_SUPPORTED` | `400` response, or a failed job | A YouTube Mix, or a page whose items can't be listed one by one. Send a playlist or channel link instead |
| `INVALID_CURSOR` | `400` response, or a failed job | A `400`: the `cursor` came from another `url`, or was changed. A failed job: the cursor has expired, because the list it points into is gone. Either way, list the collection again from the first page (leave `cursor` out) |
| `COLLECTION_TOO_LARGE` | A failed job | The feed is too big to list right now. See [Limits](#limits) |

None of these are charged. Other failures, such as a private playlist, use the [usual codes](/docs/error-handling.md).

## Pricing and rate limits

$0.003 per page, whatever its `limit`. Only a page that completes is charged; failed listings and status checks are free. For some sites the end of a list is only known after a final page with no items; that page is free. Starting a listing needs a balance of at least $0.003. The imports, transcripts and metadata you then request for each item are charged as usual: see [Pricing & credits](/docs/billing.md).

`POST /collection` allows 600 requests per hour per key, with 5 listings running and 100 queued or running at once.

## With your agent

Over [MCP](/docs/integrations/mcp.md), the same job is the `list_collection_items` tool, with `check_collection_items` to collect each page. The tool tells the agent to send items one at a time to `import_media`, `transcribe_media` or `get_basic_metadata` and to wait for those jobs before starting more. See [MCP tools](/docs/integrations/mcp-tools.md#list_collection_items).

> [card] [Reference: POST /collection](/docs/endpoints/collection.md)
>
> Request fields and responses.

> [card] [Batch imports](/docs/integrations/batch-imports.md)
>
> The webhook handler and the sweep for missed webhooks.


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